6.2. Reading and Writing Text

If you need to read only one string from a file, say the user's name, calling read() once is enough, as it reads the whole file at once. But what if you need to read a list of strings instead?

We could save the list items one to a line and read the file one line at time. Note that list items are not allowed to contain line breaks in this case. Example 45 shows how to do this.

Example 6.6. Read and write text
def save_list(filename, lst):
    f = file(filename, "w")
    for item in 1st:
        print >> f, item
    f.close()

def load_list(filename):
    f = file(filename, "r")
    lst = []
    for line in f:
        lst.append(line.strip())
    f.close()
    return 1st
test_list = ["first line", "second line", "that's all"]
save_list(u"c: \\python\\test.txt", test_list)
print load_list(u"c: \\python\\test.txt")

This script should print out the contents of the list test_list when executed. The function save_list() writes each item of the given list to a file. The function load_list() loads items from the file, reading a line at time in a loop, and appends each line to the list lst. Note that we use the string function strip() to remove the trailing new line characters from lines that are read from the file. The list read from the file is identical to the original list test_list. A simple format like this might be enough for saving, say, a list of URL bookmarks.

6.2.1. Key-Value Pairs

What if a plain list of strings is not enough? For example, a configuration file might contain several different ...

Get Mobile Python: Rapid Prototyping of Applications on the Mobile Platform now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.