Skip to content

Latest commit

 

History

History
141 lines (97 loc) · 5.76 KB

14_io.md

File metadata and controls

141 lines (97 loc) · 5.76 KB

Input and Output

There will be situations where your program has to interact with the user. For example, you would want to take input from the user and then print some results back. We can achieve this using the raw_input() function and print function respectively.

For output, we can also use the various methods of the str (string) class. For example, you can use the rjust method to get a string which is right justified to a specified width. See help(str) for more details.

Another common type of input/output is dealing with files. The ability to create, read and write files is essential to many programs and we will explore this aspect in this chapter.

Input from user

Save this program as io_input.py:

def reverse(text):
    return text[::-1]

def is_palindrome(text):
    return text == reverse(text)

phrase = raw_input("Enter text: ")
if is_palindrome(phrase):
    print("Yes, it is a palindrome.")
else:
    print("No, it is not a palindrome.")

Output:

$ python io_input.py
Enter text: racecar
Yes, it is a palindrome.

$ python io_input.py
Enter text: boat
No, it is not a palindrome.

How It Works

We use the slicing feature to reverse the text. We've already seen how we can make slices from sequences using the seq[a:b] code starting from position a to position b. We can also provide a third argument that determines the step by which the slicing is done. The default step is 1 because of which it returns a continuous part of the text. Giving a step of -1 will return the text in reverse.

The raw_input() function takes a string as argument and displays it to the user as a prompt. Then it waits for the user to type something and press the return key. Once the user has entered and pressed the return key, the raw_input() function will then return that text the user has entered.

We take that text and reverse it. If the original text and reversed text are equal, then the text is a palindrome.

Optional exercise: Checking whether a text is a palindrome should also ignore punctuation, spaces, and case. For example, "Rise to vote, sir." is a palindrome but our current program doesn't say it is. Can you improve the above program to recognize this palindrome?

Files

You can open and use files on disk for reading or writing by creating a file object and using its read and write methods appropriately to read from or write to the file. The ability to read or write to the file depends on the mode you have specified when opening the file. When you are finished with a file, you call the close method to tell Python that we are done using the file.

Example (save as io_using_file.py):

poem = '''\
If you want to make your work fun:
    Use Python!
'''

# open with 'w' mode, for writing
f = open('poem.txt', 'w')
f.write(poem)
f.close()

# if no mode is specified, 'r' = read mode is assumed by default
# let's iterate over the lines
f = open('poem.txt')
for line in f:
    print line.rstrip()
f.close()

# let's use some methods to read the contents
f = open('poem.txt')
print f.read()
f.close()

f = open('poem.txt')
print f.readlines()
f.close()

Output:

$ python io_using_file.py
If you want to make your work fun:
    Use Python!

If you want to make your work fun:
    Use Python!

['If you want to make your work fun:\n', '    Use Python!\n']

How It Works

First, open a file by using the built-in open function and 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'). We can also specify whether we are reading, writing, or appending in binary mode ('b'). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a text file and opens it in read mode.

In our example, we first open the file in w mode, use the write method to write the string to the file, then we finally close the file.

Next, we open the same file again for reading. We don't need to specify a mode because 'read text file' is the default mode. We iterate over each line using the for loop. After that, we finally close the file.

Next, we read in the file two more times, first using the read method, which reads it into a single large string, and then the readlines method which gives us a list of lines separated by "\n" newline characters.

You can also read and write the contents of poem.txt in your text editor to verify that the program is correctly writing and reading from that file on disk.

The with statement

You will notice in all the open examples so far we've had to manually specify the close method when we're done with the file. This is such a common pattern (not only with files) that a feature was added to the language to help make this easier. The with statement in Python allows you to specify a "context manager" that will automatically handle what happens before and after a block of code runs. The built-in file object can be used as a context manager in the with statement to open a file, give you access to the file object, then safely close the file even in the case of errors, without having to write your own error handling code or close call.

def f():
    with open("poem.txt") as f:
        for line in f:
            print line.rstrip()

def g():
    with open("poem.txt") as f:
        contents = f.read()
    return contents

if __name__ == "__main__":
    f()
    print g()

Output:

$ python io.py
If you want to make your work fun:
    Use Python!

If you want to make your work fun:
    Use Python!

Summary

We have discussed various types of input/output, file handling, and the with statement.