Mastering File Handling in Python: A Comprehensive Guide Part 5

Mr Stucknet
Python’s Gurus
Published in
2 min readMay 17, 2024

Manipulating pathnames

Let’s explore the abilities of pathlib a little more by means of a simple example:

# files/paths.py
from pathlib import Path
p = Path('fear.txt')

print(p.absolute())
print(p.name)
print(p.parent.absolute())
print(p.suffix)

print(p.parts)
print(p.absolute().parts)

readme_path = p.parent / '..' / '..' / 'README.rst'
print(readme_path.absolute())
print(readme_path.resolve())

Reading the result is probably a good enough explanation for this simple example:

/Users/fab/srv/lpp3e/ch08/files/fear.txt
fear.txt
/Users/fab/srv/lpp3e/ch08/files
.txt
('fear.txt',)
('/', 'Users', 'fab', 'srv', 'lpp3e', 'ch08', 'files', 'fear.txt')
/Users/fab/srv/lpp3e/ch08/files/../../README.rst
/Users/fab/srv/lpp3e/README.rst

Note how, in the last two lines, we have two different representations of the same path. The first one (readme_path.absolute()) shows two ‘..’, a single one of which, in path terms, indicates changing to the parent folder. So, by changing to the parent folder twice in a row, from …/lpp3e/ch08/files/ we go back to …/lpp3e/. This is confirmed by the last line in the example, which shows the output of readme_path.resolve().

Temporary files and directories

Sometimes, it’s very useful to be able to create a temporary directory or file when running some code. For example, when writing tests that affect the disk, you can use temporary files and directories to run your logic and assert that it’s correct, and to be sure that at the end of the test run, the test folder has no leftovers. Let’s see how to do it in Python:

# files/tmp.py
from tempfile import NamedTemporaryFile, TemporaryDirectory
with TemporaryDirectory(dir='.') as td:
print('Temp directory:', td)
with NamedTemporaryFile(dir=td) as t:
name = t.name
print(name)

The preceding example is quite straightforward: we create a temporary directory in the current one (“.”), and we create a named temporary file in it. We print the filename, as well as its full path:

$ python tmp.py
Temp directory: ./tmpz5i9ne20
/Users/fab/srv/lpp3e/ch08/files/tmpz5i9ne20/tmp2e3j8p78

Running this script will produce a different result every time. After all, it’s
a temporary random name we’re creating here, right?

That’s it for today. See you tomorrow.

if you love my blogs please consider purchasing me a book.

Python’s Gurus🚀

Thank you for being a part of the Python’s Gurus community!

Before you go:

  • Be sure to clap x50 time and follow the writer ️👏️️
  • Follow us: Newsletter
  • Do you aspire to become a Guru too? Submit your best article or draft to reach our audience.

--

--