Advertisement
pleabargain

python 3 the hard way lesson 20

May 4th, 2013
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. #exe 20
  2. #run it with something like this
  3. #C:\Python33>python PTHW20.py 1.txt.txt
  4. #
  5. #
  6. #read the errors! Typos can block you!
  7.  
  8. from sys import argv
  9.  
  10. #the script at the front is required but it's not a key word
  11. script, input_file=argv
  12.  
  13. def print_all(f):
  14.     f.seek(0) #to change the file object’s position, use f.seek(offset, from_what)
  15.  
  16. #the function is called below to iterate the lines one by one
  17. def print_a_line(line_count,f):
  18.     print (line_count, f.readline())
  19.  
  20. def rewind(f):
  21.     f.seek(0)
  22.  
  23. #open the file that was called with input_file arg
  24. #eg
  25. #C:\Python33>python PTHW20.py 1.txt.txt
  26. current_file = open(input_file)
  27. print ("Here's the file name you wanted to open {}".format(input_file))
  28.  
  29. print()
  30. print ("First, let's print the contents of the whole file:\n")
  31.  
  32. print(current_file.read())
  33. print_all(current_file) #didn't work
  34. print()
  35. print ("Now, let's rewind kind of like a tape.")
  36.  
  37. # calls the above function
  38. rewind(current_file)
  39.  
  40. print ("Let's print three lines:")
  41.  
  42. current_line = 1 #the interation worked but not current_file
  43. print_a_line (current_line, current_file)
  44.  
  45. current_line = current_line +1
  46. print_a_line(current_line, current_file)
  47.  
  48. current_line = current_line +1
  49. print_a_line(current_line, current_file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement