Python Bibliotheca
Python resources for teachers and students.

Loading a file into a list

One of the most common tasks computer programs perform is reading information from and writing information to files. Luckily, Python provides a number of useful functions to working with files. One of the most useful is the readlines() function. Here's how it works.

You don't need to load a special module to read and write files. It's all built in. The readlines() function doesn't take any arguments. It's only job is to read a file line by line into a list of strings. Let's say we've got a file named groceryList.txt that contains the following lines:

bananas
apricots
Tylenol
Cap'n Crunch
milk
veal shank

The following program would open that file for reading and load all of those words into a list named shoppingList:

file = open('groceryList.txt', 'r')
shoppingList = file.readlines()

There's nothing magical about the word file here. I could have just as easily used f = open('groceryList.txt', 'r'), or any other word for that matter, but file seems to make sense.

Once the file is loaded in the list, you can use all of the ordinary list functions that you've learned about. Have a look at this sample session:

>>> file =open('groceryList.txt', 'r')
>>> shoppingList = file.readlines()
>>> shoppingList[0]
'bananas\r\n'
>>>

What's up with the \r\n business? Those are the carriage return and line feed characters that DOS files use to mark the end of a line. (On a Unix machine, the end of the line is marked by a \n only.) So if you want to have just the word without the end-of-line characters, you need to slice them off like this:

>>> shoppingList[0][:-2]
'bananas'
>>>

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster