to close the file. File write calls return the number of characters or bytes written (which
we’ll sometimes omit in this book to save space), and as we’ll see, close calls are often
optional, unless you need to open and read the file again during the same program or
session:
C:\temp> python
>>> file = open('data.txt', 'w') # open output file object: creates
>>> file.write('Hello file world!\n') # writes strings verbatim
18
>>> file.write('Bye file world.\n') # returns number chars/bytes written
18
>>> file.close() # closed on gc and exit too
And that’s it—you’ve just generated a brand-new text file on your computer, regardless
of the computer on which you type this code:
C:\temp> dir data.txt /B
data.txt
C:\temp> type data.txt
Hello file world!
Bye file world.
There is nothing unusual about the new file; here, I use the DOS dir and type com-
mands to list and display the new file, but it shows up in a file explorer GUI, too.
In the open function call shown in the preceding example, the first argument
can optionally specify a complete directory path as part of the filename string. If we
pass just a simple filename without a path, the file will appear in Python’s current
working directory. That is, it shows up in the place where the code is run. Here, the
directory C:\temp on my machine is implied by the bare filename data.txt, so this ac-
tually creates a file at C:\temp\data.txt. More accurately, the filename is relative to the
current working directory if it does not include a complete absolute directory path. See
“Current Working Directory” on page 104 (Chapter 3), for a refresher on this topic.
Also note that when opening in w mode, Python either creates the external file if it does
not yet exist or erases the file’s current contents if it is already present on your machine
(so be careful out there—you’ll delete whatever was in the file before).
Notice that we added an explicit \n end-of-line character to lines written to the
file; unlike the print built-in function, file object write methods write exactly what they
are passed without adding any extra formatting. The string passed to write shows up
character for character on the external file. In text files, data written may undergo line-
end or Unicode translations which we’ll describe ahead, but these are undone when
the data is later read back.
Output files also sport a writelines method, which simply writes all of the strings in a
list one at a time without adding any extra formatting. For example, here is a write
lines equivalent to the two write calls shown earlier:
file.writelines(['Hello file world!\n', 'Bye file world.\n'])
Opening.
Writing.
138 | Chapter 4: File and Directory Tools