14-io.pd 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. # Input Output
  2. 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 `input()` and `print()` functions respectively.
  3. 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.
  4. 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.
  5. ## Input from user
  6. Save this program as `user_input.py`:
  7. ~~~python
  8. def reverse(text):
  9. return text[::-1]
  10. def is_palindrome(text):
  11. return text == reverse(text)
  12. something = input('Enter text: ')
  13. if (is_palindrome(something)):
  14. print("Yes, it is a palindrome")
  15. else:
  16. print("No, it is not a palindrome")
  17. ~~~
  18. Output:
  19. ~~~
  20. $ python3 user_input.py
  21. Enter text: sir
  22. No, it is not a palindrome
  23. $ python3 user_input.py
  24. Enter text: madam
  25. Yes, it is a palindrome
  26. $ python3 user_input.py
  27. Enter text: racecar
  28. Yes, it is a palindrome
  29. ~~~
  30. How It Works:
  31. We use the slicing feature to reverse the text. We've already seen how we can make [slices from sequences](#sequence) 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 negative step, i.e., `-1` will return the text in reverse.
  32. The `input()` function takes a string as argument and displays it to the user. 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 `input()` function will then return that text the user has entered.
  33. We take that text and reverse it. If the original text and reversed text are equal, then the text is a [palindrome]([http://en.wiktionary.org/wiki/palindrome).
  34. Homework exercise
  35. : Checking whether a text is a palindrome should also ignore punctuation, spaces and case. For example, "Rise to vote, sir." is also a palindrome but our current program doesn't say it is. Can you improve the above program to recognize this palindrome?
  36. *Hint (Don't read) below*
  37. Use a tuple (you can find a list of *all* punctuation marks here [punctuation](http://grammar.ccc.commnet.edu/grammar/marks/marks.htm)) to hold all the forbidden characters, then use the membership test to determine whether a character should be removed or not, i.e. forbidden = ('!', '?', '.', ...).
  38. ## Files
  39. You can open and use files for reading or writing by creating an object of the `file` class and using its `read`, `readline` or `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 for the file opening. Then finally, when you are finished with the file, you call the `close` method to tell Python that we are done using the file.
  40. Example (save as `using_file.py`):
  41. ~~~python
  42. poem = '''\
  43. Programming is fun
  44. When the work is done
  45. if you wanna make your work also fun:
  46. use Python!
  47. '''
  48. f = open('poem.txt', 'w') # open for 'w'riting
  49. f.write(poem) # write text to file
  50. f.close() # close the file
  51. f = open('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default
  52. while True:
  53. line = f.readline()
  54. if len(line) == 0: # Zero length indicates EOF
  55. break
  56. print(line, end='')
  57. f.close() # close the file
  58. ~~~
  59. Output:
  60. ~~~
  61. $ python3 using_file.py
  62. Programming is fun
  63. When the work is done
  64. if you wanna make your work also fun:
  65. use Python!
  66. ~~~
  67. How It Works:
  68. 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 text mode (`'t'`) or 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 't'ext file and opens it in 'r'ead mode.
  69. In our example, we first open the file in write text mode and use the `write` method of the file object to write to the file and then we finally `close` the file.
  70. 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 read in each line of the file using the `readline` method in a loop. This method returns a complete line including the newline character at the end of the line. When an *empty* string is returned, it means that we have reached the end of the file and we 'break' out of the loop.
  71. By default, the `print()` function prints the text as well as an automatic newline to the screen. We are suppressing the newline by specifying `end=''` because the line that is read from the file already ends with a newline character. Then, we finally `close`the file.
  72. Now, check the contents of the `poem.txt` file to confirm that the program has indeed written to and read from that file.
  73. ## Pickle
  74. Python provides a standard module called `pickle` using which you can store **any** Python object in a file and then get it back later. This is called storing the object *persistently*.
  75. Example (save as `pickling.py`):
  76. ~~~python
  77. import pickle
  78. # the name of the file where we will store the object
  79. shoplistfile = 'shoplist.data'
  80. # the list of things to buy
  81. shoplist = ['apple', 'mango', 'carrot']
  82. # Write to the file
  83. f = open(shoplistfile, 'wb')
  84. pickle.dump(shoplist, f) # dump the object to a file
  85. f.close()
  86. del shoplist # destroy the shoplist variable
  87. # Read back from the storage
  88. f = open(shoplistfile, 'rb')
  89. storedlist = pickle.load(f) # load the object from the file
  90. print(storedlist)
  91. ~~~
  92. Output:
  93. ~~~
  94. $ python3 pickling.py
  95. ['apple', 'mango', 'carrot']
  96. ~~~
  97. How It Works:
  98. To store an object in a file, we have to first `open` the file in 'w'rite 'b'inary mode and then call the `dump` function of the`pickle` module. This process is called *pickling*.
  99. Next, we retrieve the object using the `load` function of the `pickle` module which returns the object. This process is called *unpickling*.
  100. ## Summary
  101. We have discussed various types of input/output and also file handling and using the pickle module.
  102. Next, we will explore the concept of exceptions.