Py-Tut-009

Back to Learning Python

File Input/Output (I/O)
Python supports many ways to input and output data beyond typing input and displaying text on the screen as we have done so far. We will now look at the most basic form of file I/O. Rather than print to the screen, we will print to a file and we will then read the contents of the file back to the screen. For our purposes right now, we will only deal with reading and writing text data.

Open
The open function is another built-in function in Python. We will create a variable that will represent the file and use open to read and/or write to it.

Before moving on, make sure you read "7.2 Reading and Writing Files" and "7.2.1 Methods of File Objects" from the official Python Documentation website. Make certain you understand important details like the attributes when we read/write/append to a file as well as how many lines we can read/write to a file at a time. It is good practise to always close files when you are done with them.

Reading Contents of a File to the Screen
In order to read the contents of a text file to the screen, you must first open the file. You then print the contents and finally close the file. For the following example, click to download the attached text file and save it to the root directory of your computer.

code format="python" myFile = open ('/Py-Tut-009-openread01.txt', 'r')

print myFile.read

myFile.close code



Writing to a File
When writing to a file it is extremely important understand the difference between the attributes 'w' and 'a'. The former will overwrite any previously existing data and create a new file and the latter will append to existing data. You cannot retrieve any files you have lost by making this mistake!

The following example modifies the example from exercise 7 to write to a text file rather than the screen.

code format="python" myFile = open ('/myprogram.txt', 'w')

myNumbers = [3, 12, 1, 10, 11, 8, 4, 9, 7, 6, 2, 5] months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

myFile.write ( "The len of myNumbers is: " + str(len(myNumbers)) + '\n') myFile.write ( "The min of myNumbers is: " + str(min(myNumbers)) + '\n') myFile.write ( "The min of months is:" + str(min(months)) + '\n') myFile.write ( "The max of myNumbers is:" + str(max(myNumbers)) + '\n') myFile.write ( "The max of months is:" + str(max(months)) + '\n') myFile.write ( "The sorted of myNumbers is:" + str(sorted(myNumbers)) + '\n') myFile.write ( "The sorted of months is:" + str(sorted(months)) + '\n')

myFile.close

code

Assignment 9a
Explain how the attributes "r", "w", "a" work for the open function and why they are important.

Assignment 9b
Modify assignment 8 so that it writes the contents to a text file.

Assignment 9c
Modify assignment 9b so that it prints the content of the file to the screen.

Back to Learning Python