Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Using file

Example 12.1. Using files

#!/usr/bin/python
# Filename: using_file.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') # open for 'w'riting f.write(poem) # write text to file
f.close() # close the file

f = file('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line, # Notice comma to avoid automatic newline added by Python f.close() # close the file

Output

$ python using_file.py Programming is fun
When the work is done
if you wanna make your work also fun:

use Python!

How It Works

First, we create an instance of the file class by specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode ('r'), write mode ('w') or append mode ('a'). There are actually many more modes available andhelp(file) will give you more details about them.

We first open the file in write mode and use thewrite method of thefile class to write to the file and then we finallyclose the file.

Next, we open the same file again for reading. If we don't specify a mode, then the read mode is the default one. We read in each line of the file using thereadline method, in a loop. This method returns a complete line including the newline character at the end of the line. So, when an empty string is returned, it indicates that the end of the file has been reached and we stop the loop.

Notice that we use a comma with the print statement to suppress the automatic newline that the print statement adds because the line that is read from the file already ends with a newline character. Then, we finallyclose the file.

Now, see the contents of thepoem.txt file to confirm that the program has indeed worked properly.