Section 3: Writing Data to Files
Table of Contents >
Chapter 6 > Section 3
We have seen how data stored in files can be read and processed by a
Python program. Similarly, data that is produced by a Python program
can be written to file where it will persist after the program has been
terminated.
Before we can write data to a file, we must first open it for
writing. We use the same function that we used to open a file for
reading but specify the
'w'
or write mode:
with open('myFile.txt', 'w') as f:
...f
When we open a file for writing, it is created for us if it does not
already exist. Be careful when opening an existing file for writing
as anything previously stored in the file will be erased when the file is
opened. If you wish to append new data to the end of the file, use
the
'a'
or append mode.
The
file
class has a
write
method that writes
a string to a file. We have seen that it is convenient to read data
from a file a line at a time, although this is not the only way that it
can be done. When it comes to writing data to a file, we are free to
choose the level of granularity - from single character, to word, to line,
to entire contents of the file - it depends what is stored in the string
that we pass to the write method.
As a simple example,
Code
Explorer 7.2 shows a Python function that makes a copy of a
file.
Some comments are in order:
- When designing the tests, note that we have used a
StringIO
object to represent the input and output file. When constructing
the StringIO
object that represents the output file, we
passed an empty string as a parameter, thereby simulating an empty
file.
- The
StringIO
class has a method getvalue()
that returns the entire contents of the "file". We use this in
the tests to ensure that the output file contains an exact copy of the
input file.
- We would not normally copy a file this way. Operating systems
provide methods for copying files that are far more efficient.
Assuming that we want to copy the file
data.txt
to a file
named
dataCopy.txt
, we call our
copy_file
function from the Python shell as follows:
>>> with open('data.txt', 'U') as inf:
>>> with open('dataCopy.txt', 'w') as
outf:
>>>
copy_file(inf, outf)
Again, the with statement ensures that the files
data.txt
and
dataCopy.txt
are closed after the call to
copy_file
terminates.