Munch Lab

Python exercise: Reading and writing files

With all you have learned so far, there is little extra challenge now in learning to work with files. This page contains both some explanation of the topics we cover and some exercises for you to do. Read through the page and complete the exercises at the end. Spend any remaining time playing around on the code examples in the explanatory text. Remember that the key here is learning by doing. Type some of the code examples into your IDLE editor and try them out yourself — and be curious. Try and see what happens if you change things a bit.

Reading from a file

You can open a existing file you want to read like this:

f = open('filename', 'r')

The 'r' indicates that you want to read from the file. open returns a file object with methods that allows you to interact with the file. You can loop through all the lines in the file using a for loop:

for line in f:
    print line

or you can read in all the lines and get them in a list using the readlines() method:

lines = f.readlines()

or even read in the entire file as a string using the read() method:

s = f.read()

Which approach you prefer is a matter of taste and a question of what you want to do with the content of the file. One thing to notice is that once you have opened a file you can only read it once (there are ways to read it again that we do not cover here). If you want to read it again close it and open it again. To close a file all the close() method on the file object like this:

f.close()

Writing to a file

If you want to write to a file, you must open it for writing like this:

f = open('filename', 'w')

Here the the second argument, 'w', specifies that the file should be opened for writing. To write something to the file use the write() method:

f.write("This is something we want to write\n")

Notice that we put a newline character at the end of the string so that it becomes a proper line in the file. You can also write several lines at a time:

f.write("This is one line\nThis is another\n")

An alternative way to write to a file is to re-direct print statements to the file, so the result of the print is sent to the file instead of the terminal. Such a print statement looks like this:

print >> f, "What you want to write to the file."

Notice that we do not put an new line at the end of the string here. As you have probably noticed yourself print does that for us. Once you are done with writing the file, close it with the close() method:

f.close()

Exercises

To test your functions you can download the files used below here: printFileExample.txt sumColumnExample.txt sumAllExample.txt readColumnExample.txt zenOfPython.txt filterFileExample.txt

printFile(filename)

Write a function, printFile(filename), that prints the contents of file named “filename” to screen. Hint: You will probably want to use “print” to print the lines of the file. If you do this you will probably get a lot of empty lines. This is because print adds a newline and you also print the newlines already present in your input file. To avoid print adding a newline you can add a comma at the end of your print statement. Like this:

print 'Hello, world!',

Example usage:

printFile('printFileExample.txt')This is a small file.It has a few lines.Like this one.

sumColumn(filename)

Write a function, *sumColumn(filename), that should read a file that has exactly one integer on each line and return the sum of these integers. Hint: You will read strings from the file, but want to sum integers. To convert strings to integers use *int()* like this:

int('42')

Example usage:

print sumColumn('sumColumnExample.txt')

42

sumAll(filename)

Write a function, sumAll(filename), that should read a file containing only integers and return the sum of all these integers. Hint: Use str.split() to split a line containing multiple integers. Example usage:

print sumAll('sumAllExample.txt')

1262

readColumn(filename, columnNo)

Write a function, readColumn(filename, columnNo). The file named by filename should contain columns of integers separated by whitespace. The function should read the column number “columnNo”, convert it to integers and return it as a list. Example usage:

print readColumn('readColumnExample.txt', 1)

[12, 1, 4, 2, 3, 0, 1, 8]

countWord(filename, word)

Write a function, countWord(filename, word), that should count and return how many times word appears in file called filename. Example usage:

print countWord('zenOfPython.txt', 'the')

5

writeName(filename, firstName, lastName)

Write a function, writeName(filename, firstName, lastName), that writes the full name consisting of firstName and lastName to a single line in a file called filename. Example usage:

writeName('writeNameTest.txt', 'Charles', 'Darwin')
printFile('writeNameTest.txt')

Charles Darwin

writeColumn(filename, column)

Write a function, writeColumn(filename, column), that writes the elements of the list column to a file called filename. There should be one element per line. Example usage:

writeColumn('writeColumnTest.txt', [1, 1, 2, 3])
printFile('writeColumnTest.txt')

1 1 2 3

filterFile(fromFilename,toFilename,word)

Write a function, filterFile(fromFilename, toFilename, word). It should copy all lines that contain the word word from file fromFilename to file toFilename. Example usage:

filterFile('filterFileExample.txt', 'filterFileTest.txt', 'line') printFile('filterFileTest.txt')

this is a line of words
this is also a line of words
Solutions: Download linked file

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: