Next / Previous / Contents / TCC Help System / NM Tech homepage

9.3. Writing files

To create a disk file, open the file using a statement of this general form:

F = open ( filename, "w" )

The second argument, "w", specifies write access. If possible, Python will create a new, empty file by that name. If there is an existing file by that name, and if you have write permission to it, the existing file will be deleted.

To write some content to the file you are creating, use this method:


where s is any string expression.

>>> sports = open ( "sportfile", "w" )
>>> sports.write ( "tennis\nrugby\nquoits\n" )
>>> sports.close()
>>> sportFile = open ( "sportfile" )
>>> sportFile.readline()
>>> sportFile.readline()
>>> sportFile.readline()
>>> sportFile.readline()


The data you have sent to a file with the .write() method may not actually appear in the disk file until you close it.

This is due to a mechanism called buffering. Python accumulates the data you have sent to the file, until a certain amount is present, and then it “flushes” that data to the physical file by writing it. Python also flushes the data to the file when you close it.

If you would like to make sure that the data you have written to the file is actually physically present in the file without closing it, call the .flush() method on the file object.

Here is a lengthy example demonstrating the action of the .flush() method.

>>> sporting = open('sports', 'w')
>>> sporting.write('golf\n')
>>> echo = open('sports')
>>> echo.close()
>>> sporting.flush()
>>> echo = open('sports')
>>> echo.close()
>>> sporting.write('soccer')
>>> sporting.close()
>>> open('sports').read()

Note that you must explicitly provide newline characters in the arguments to .write().