Advertisement
namchef

LPTHW_ex16

Sep 28th, 2011
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. # close -- closes the file
  2. # read -- reads the contents of the file, you can assign the result to a variable.
  3. # readline -- reads just one line of a text file
  4. # truncate -- empties the file
  5. # write(stuff) -- writes stuff to the file
  6.  
  7. from sys import argv
  8.  
  9. script, filename=argv
  10.  
  11. print "We're going to erase %r." % filename
  12. print "If you don't want that, hit CTRL-C (^C)."
  13. print "If you do want that, hit RETURN."
  14.  
  15. raw_input("?")
  16.  
  17. ###?Traceback (most recent call last):
  18. ###  File "ex16.py", line 15, in <module>
  19. ###    raw_input("?")
  20. ### KeyboardInterrupt
  21.  
  22.  
  23. print "Opening the file..."
  24. target=open(filename, 'w')
  25.  
  26. print "Truncating the file. Goodbye!"
  27. #target.truncate()
  28.  
  29. print "Now I'm going to ask you for three lines."
  30.  
  31. line1=raw_input("line 1: ")
  32. line2=raw_input("line 2: ")
  33. line3=raw_input("line 3: ")
  34.  
  35. print "I'm going to write these to the file."
  36.  
  37. # target.write(line1)
  38. # target.write("\n")
  39. # target.write(line2)
  40. # target.write("\n")
  41. # target.write(line3)
  42. # target.write("\n")
  43.  
  44. # ec.3 : b=line1+'\n'+line2+'\n'+line3
  45. # ec.4 : target.write(b)
  46.  
  47. target.write(line1+'\n'+line2+'\n'+line3)
  48.  
  49. print "And finally, we close it."
  50. target.close()
  51.  
  52.  
  53.  
  54. ## extra credit
  55. # Write a script similar to the last exercise that uses read and argv to read the file you just created.
  56. # There's too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of 6.
  57. # Find out why we had to pass a 'w' as an extra parameter to open. Hint: open tries to be safe by making you explicitly say you want to write a file.
  58. # If you open the file with 'w' mode, then do you really need the target.truncate()? Go read the docs for Python's open function and see if that's true.
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement