05: Handling Files


Saving and transferring information can be difficult when done exclusively inside a program. Though it is faster, the stored data often dies with the program. A basic way around this is seen in things like Cookie files, where the browser stores some information to your computer in a RTF (Rich Text File). Let’s see how we can read and write to such files.

Loading the File

Python makes it pretty easy to load a file from your computer and use it inside a program. All we need is the directory that the file is saved under. If you place the file in the same directory (inside the same folder) as the Python .py file that you’re working with, you only need to reference its name. For 1D04, always have the file you’re accessing inside the same directory (folder) as your .py file.

To load a text (.txt) file from the same directory as the .py file:

Our directory should look something like this:

myFolder/ loadFile.py myFile.txt

To load a text (.txt) file from the same directory as the .py file:

# Load file: myFile.txt 
f = open("myFile.txt", "r") 

f.close() #Closes the file so we can use it elsewhere

This gives us Read permission to the file. The permissions are denoted by the ‘r’ argument in our open() function. There are several other arguments for this (here), but we won’t need them yet.

Now we’ve done it! Our loaded file is stored in the variable file. Remember to close your file, as it will be inaccessible from Windows if it’s open in Python!

Finding a Path

Note: This is only for those looking to specify an existing file. For 1D04, always place your .txt file in the same directory as your .py file.

Each file has a unique path. Every path starts at the root of your computer, usually denoted by a slash or a tilda (~). If you’re looking for the path of a file, it can often be found under “properties”, “more info”, or “get info” depending on your OS.

If you’re still unable to find the path, think of a computer like a filing cabinet.

• “My Computer” is the whole filing cabinet.
• Your “C” drive like a drawer inside My Computer.
• Inside of your C drive, there are lots of folders
• Inside each folder, there can be more folders and files, and so on.

We always point to our files from the C drive. For example:
C:\Users\Jamie Counsell\Python\myFile.txt

In Python, we will just give it the path:
\Users\Jamie Counsell\Python\myFile.txt

Or in *nix environments (MacOSX and Linux)
/Users/Jamie Counsell/Python/myFile.txt

/Users/Jamie Counsell/Python/myFile.txt

# Load file: myFile.txt 
file = open("/Users/Jamie Counsell/test.txt", "r")

Reading the File

Once we’ve loaded the file, we may want to read or edit its contents. Python makes this pretty easy as well. There are three ways to read a Python file:


Reads the whole file and stores it to a string. This can not be done more than once, as there is no more of the file left to read!


This reads a single line out of a file. In .txt files, a line is separated by a newline character (\n), which is what happens when you press the Enter key in your text editor. The newline character (\n) is left at the end of the string returned by readline().


This reads every line in the file and stores them as a list of strings.

Here’s what is inside myFile.txt:

this is text 

Let’s try it in the Python Shell:

#Open the file 
f = open("myFile.txt", 'r') 
print f.read() 

#Remember we just read the whole file, so we have to open it again 
f = open("myFile.txt", 'r') 
print f.readline() 

#Now that we've read one line of the file, we must open it 
#again so that line is included again when we readlines() 
f = open("myFile.txt", 'r') 
print f.readlines()

And here’s our output:

'line1\nline2\nthis is text\nline4' 


['line1\n', 'line2\n', 'this is text\n', 'line4']

As expected, the first command printed the entire file. You can see the newline characters in the resulting string. The second example printed only one line, but would print more if we called it again (maybe in a FOR loop). The last command broke the file down into strings inside a list by line.

Writing to the File

Let’s say we want to change the contents of a file. We can modify or rewrite the file entirely using the write() command. We also must open the file with write permissions (‘w’). WARNING: OPENING A FILE WITH WRITE PERMISSIONS WILL CLEAR ALL UNREAD CONTENT INSIDE. Basically, make sure you save the contents of the file to manipulate and write back before you close it. Let’s rewrite the file entirely.

#Open the file 
f = open("myFile.txt", 'w') 
f.write("It's all gone!") 

Now we can look inside the file:

It's all gone!

There we go. When we opened the file, we cleared all of its contents. We then wrote a new string into the file, and closed it to save the changes. Notice that there is no trace of the old content. If we wanted to keep some of that content, we would have to save it to a variable first:

#Open the file and save its contents
f = open("myFile.txt", 'r') 
content = f.read() 

#Open the file again for reading and add content
f = open("myFile.txt", 'w') 
newContent = content + "nThis is the last line" 

#Don't forget to close your files!

Notice here that we saved the old content to content, and added new content at the end of the file by creating a new string “newContent” which contained the old content and some new text. Now, the file will contain the original material, with the added content in “\n This is the last line”. Try it out to see for yourself!

It is often good practice to manipulate files using this method. Open the file, then process it, and then close it. Always remember to close your file when you’re done!