Reading and writing to a file

Now that we know how to open a file, let's see a couple of different ways that we have to 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)

A first approach uses the print function, which you've seen plenty of times in the previous chapters. 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 effects on the file, instead of the default sys.stdout, which, when executed on a console, is mapped to it.

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

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(' '.join(lines))

In the previous example, we first open fear.txt and collect its content into a list, line by line. Notice that this time, I'm calling a more precise method, rstrip(), as an example, to make sure I 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,  . 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 than  , 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 of them that might be missing in the copy?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset