Jump to content

An Introduction to Python For Undergraduate Engineers/Reading/Writing to Files

From Wikibooks, open books for an open world

You may want your program to input/output data to/from a file. For example if your program calculates something repeatedly you may want it to store the value from each calculation in a file rather than let them all print on screen. This can be done using the open() command. For example:

   datafile = open("data.txt",'w')

This creates a file called 'data.txt' and makes it available for writing (the w parameter). The file can then be accessed by your program using the reference 'datafile'. To write to the file we then use the write() command in the following way:

   datafile.write("Add this text to the file")

This will add the text in quotation marks to the end of the file. It is important that you use the following command to close the file when you are done. If you are using Windows™ and you don't do this, nothing will be written to the file!

   datafile.close()

Functions to read/write to files are shown in the list below:

Command Description
open("filename",'w') Opens a file and makes it available for writing to.
open("filename",'r') Opens a file and makes it available for reading from.
reference.write("text") Writes the text "text" to the file that is referenced to by 'reference'.
reference.readline() Returns the next line of the file.
reference.read() Returns the entire file as a single string.
reference.readlines() Returns a list of strings. Each string is one line of the file.
reference.close() Closes the file.