In many cases, you will want your program to interact with the user (possibly yourself). You will get input from the user and then print some results. We can use the Raw_input and print statements separately to accomplish these functions. For output, you can also use a variety of str (string) classes. For example, you can use the Rjust method to get a string that is right-aligned by a certain width. Use Help (str) for more details.
Another commonly used input/output type is the processing of files. The ability to create, read, and write files is necessary for many programs, and we will explore how to implement them in this chapter.
File
You can open a file by creating an object of the file class, using the read, ReadLine, or write methods of the file class to properly read and write files. The ability to read and write files depends on the pattern you specify when you open the file. Finally, when you are done with the file, you call the Close method to tell Python that we have finished using the file.
Working with files
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
(source file: code/using_file.py)
Output
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!