Mastering File Handling in Python: A Comprehensive Guide Part 2

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

Using a context manager to open a file

Let’s admit it: the prospect of having to disseminate our code with try/finally blocks is not one of the best. As usual, Python gives us a much nicer way to open a file in a secure fashion: by using a context manager. Let’s see the code first:

# files/open_with.py
with open('fear.txt') as fh:
for line in fh:
print(line.strip())

This example is equivalent to the previous one, but reads so much better.
The open() function is capable of producing a file object when invoked by a context manager, but the true beauty of it lies in the fact that fh.close() will be called automatically for us, even in the case of errors.

Reading and writing to a file

Now that we know how to open a file, let’s see a couple of different ways in which we can read and write to it:

# files/print_file.py
with open('print_example.txt', 'w') as fw:
print('Hey I am printing into a file!!!', file=fw)

After obtaining a file object, this time specifying that we intend
to write to it (‘w’), we can tell the call to print() to direct its output to the file, instead of to the standard output stream as it normally does.

In Python, the standard input, output, and error streams are
represented by the file objects sys.stdin, sys.stdout, and
sys.stderr. Unless input or output is redirected, reading from
sys.stdin usually corresponds to reading from the keyboard
and writing to sys.stdout or sys.stderr usually prints to the
console screen.

The previous code has the effect of creating the print_example.txt file if it doesn’t exist, or truncating it in case if, and writes the line Hey I am printing into a file!!! into it.

Truncating a file means erasing its contents without deleting it.
After truncation, the file still exists on the filesystem, but it’s empty

This is all nice and easy, but not what we typically do when we want to write to a file. Let’s see a much more common approach:

# files/read_write.py
with open('fear.txt') as f:
lines = [line.rstrip() for line in f]
with open('fear_copy.txt', 'w') as fw:
fw.write('\n'.join(lines))

In this example, we first open fear.txt and collect its content into a list, line by line. Notice that this time, we are calling a different method, rstrip(), as an example, to make sure we only strip the whitespace on the right-hand side of every line.

In the second part of the snippet, we create a new file, fear_copy.txt, and we write to it all the lines from the original file, joined by a newline, \n. Python is gracious and works by default with universal newlines, which means that even though the original file might have a newline that is different to \n, it will be translated automatically for us before the line is returned. This behavior is, of course, customizable, but normally it is exactly what you want. Speaking of newlines, can you think of one that might be missing in the copy?

That’s it for today. See you tomorrow.

if you love my blogs consider buying me a book. Thanks.

--

--