>A Byte of Python

Chapter 12. Input/Output

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.