Table of Contents
There will be lots of instances where your program needs to interact with the user (which could be yourself) and we have already seen how to do this with the help of the raw_input function and the print statement. You can also the various string methods i.e. methods of the str class. For example, you can use the rjust method of the str class to get a string which is right justified to a specified width. See help(str) for more details.
Another common type of input/output you need to do is with respect to files. The ability to create, read and write files is essential to many programs and we will explore this aspect in this chapter.
You can open and use files for reading or writing by first creating an object of the file class. Then we use the read, readline, or write methods of the file object to read from or write to the file depending on which mode you opened the file in. Then finally, when you are finished the file, you call the close method of the file object.
Example 12.1. Using files
#!/usr/bin/python # Filename: fileob.py poem = '''\ Programming is fun When the work is done if (you wanna make your work also fun): use Python! ''' f = file('poem.txt', 'w') f.write(poem) f.close() f = file('poem.txt') # the file is opened in 'r'ead mode by default while True: line = f.readline() if len(line) == 0: # Length 0 indicates EOF break print line, # So that extra newline is not added f.close()
$ python fileob.py Programming is fun When the work is done if (you wanna make your work also fun): use Python!
First, we create an instance of the file class and specify the name of the file we want to access and the mode in which we want to open the file. The mode can be a read mode('r'), write mode ('w') or the append mode ('a'). There are actually many more modes available and help(file) should give you more details.
In this case, we open the file in write mode. Then, we use the write method of the file object to write to the file. Finally, we call the close method to finish.
Then, we open the same file again for reading. Notice that if we don't specify the mode, then the read mode is the default one. We read each line of the file using the readline method in a loop. This method returns a complete line, including the newline character. So, even an empty line will have a single character which is the newline. The end of the file is indicated by a completely empty string which is checked for using len(line) == 0.
Notice that we use a comma with the print statement to suppress the automatic newline of the print statement because the line that is read from the file already ends with a newline character. Then, we close the file. See the poem.txt file to confirm that the program has indeed worked properly.