Mastering File Handling in Python: A Comprehensive Guide Part 3

Mr Stucknet
Python’s Gurus
Published in
3 min readMay 15, 2024

Reading and writing in binary mode:

Notice that by opening a file passing t in the options (or omitting it, as it is the default), we’re opening the file in text mode. This means that the content of the file is treated and interpreted as text.

If you wish to write bytes to a file, you can open it in binary mode. This is a common requirement when you deal with files that don’t just contain raw text, such as images, audio/video, and, in general, any other proprietary format.

In order to handle files in binary mode, simply specify the b flag when opening them, as in the following example:

# files/read_write_bin.py
with open('example.bin', 'wb') as fw:
fw.write(b'This is binary data...')
with open('example.bin', 'rb') as f:
print(f.read()) # prints: b'This is binary data...'

In this example, we are still using text as binary data, for simplicity, but it could be anything you want. You can see it’s treated as binary by the fact that you get the b’This …’ prefix in the output.

Protecting against overwriting an existing file

As we have seen, Python gives us the ability to open files for writing. By using the w flag, we open a file and truncate its content. This means the file is overwritten with an empty file, and the original content is lost. If you wish to only open a file for writing if it doesn’t already exist, you can use the x flag instead, as in the following example:

# files/write_not_exists.py
with open('write_x.txt', 'x') as fw:
fw.write('Writing line 1')
with open('write_x.txt', 'x') as fw:
fw.write('Writing line 2')

If you run this snippet, you will find a file called write_x.txt in your directory, containing only one line of text. The second part of the snippet, in fact, fails to execute. This is the output we get on our console (the file path has been shortened for editorial purposes):

$ python write_not_exists.py
Traceback (most recent call last):
File "/.../ch08/files/write_not_exists.py", line 6, in <module>
with open('write_x.txt', 'x') as fw:
FileExistsError: [Errno 17] File exists: 'write_x.txt'

Checking for file and directory existence

If you want to make sure a file or directory exists (or doesn’t), the pathlib module is what you need. Let’s see a small example:

# files/existence.py
from pathlib import Path
p = Path('fear.txt')
path = p.parent.absolute()
print(p.is_file()) # True
print(path) # /Users/fab/srv/lpp3e/ch08/files
print(path.is_dir()) # True
q = Path('/Users/fab/srv/lpp3e/ch08/files')
print(q.is_dir()) # True

The preceding snippet is quite interesting. We create a Path object that we set up with the name of the text file we want to inspect. We use the parent() method to retrieve the folder in which the file is contained, and we call the absolute() method on it, to extract the absolute path information.

We check if ‘fear.txt’ is a file, and the folder in which it is contained is indeed a folder (or directory, which is equivalent).

The old way to do these operations was to use the os.path module from the standard library. While os.path works on strings, pathlib offers classes representing filesystem paths with semantics appropriate for different operating systems. Hence, we suggest using pathlib whenever possible, and reverting to the old way of doing things only when there is no alternative.

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.

--

--