Advertisement
timber101

Gimme5 - File Handling

Feb 19th, 2022
786
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. #file handling
  2. """
  3. 1a.  Create a new program that asks you to enter then name of a pet
  4. 1b.  Change the program so that the pets name is then saved to an external file, called my_pet.txt
  5.  
  6. 2a.  Verify that your pets name has been added to the file
  7. 2b.  Run the program again and add another pet, can be called anything!
  8. 2c.  Verify again and notice the way the data is saved..  (should all be squished together!”
  9.  
  10. 3a. Change your code to include the new line character (hint below if needed)
  11. 3b.  Change code again to loop taking in new pet names until someone enters “STOP”
  12. 3c.  Verify the file, if you have added STOP to the file, change your code so that this doesn’t appear
  13.  
  14. 4a.  Now create some code the read in the whole file and print out the contents, check that its the same as your my_pet.txt file.
  15. 4b.  Change read to readline and prove that you are able to read the file in one line at a time
  16.  
  17. 5a.  Change readline to readlines and prove that you are able to see a list of its contents.
  18. 5b.  Now create some code that removes the “\n” from each element of the list.
  19. 5c.  Now apply one of your favourite list methods to the list.  (eg Len, sort, [0]…..)
  20. """
  21.  
  22. """
  23. file = open("my_new_names_file.txt","a") # a append, r - read only, w - write
  24. name = ""
  25.  
  26. while name != "xxx":
  27.    name = input("Enter a name >>  ")
  28.    if name != "xxx":
  29.        file.write(name + "\n")
  30. file.close()
  31. """
  32.  
  33. # read a file in
  34.  
  35. file = open("my_new_names_file.txt","r")
  36.  
  37. my_list = file.readlines() # read all in, readline - one at a time, readlines - all in as a list
  38.  
  39. file.close()
  40.  
  41. print(my_list)
  42.  
  43. #loop through
  44. for each in my_list:
  45.     print(each[:len(each)-1])
  46.  
  47. #make_new_list
  48. my_new_list = []
  49. for each in my_list:
  50.     my_new_list.append(each[:len(each)-1])
  51.    
  52. print(my_new_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement