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

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: