Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #file handling
- """
- 1a. Create a new program that asks you to enter then name of a pet
- 1b. Change the program so that the pets name is then saved to an external file, called my_pet.txt
- 2a. Verify that your pets name has been added to the file
- 2b. Run the program again and add another pet, can be called anything!
- 2c. Verify again and notice the way the data is saved.. (should all be squished together!”
- 3a. Change your code to include the new line character (hint below if needed)
- 3b. Change code again to loop taking in new pet names until someone enters “STOP”
- 3c. Verify the file, if you have added STOP to the file, change your code so that this doesn’t appear
- 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.
- 4b. Change read to readline and prove that you are able to read the file in one line at a time
- 5a. Change readline to readlines and prove that you are able to see a list of its contents.
- 5b. Now create some code that removes the “\n” from each element of the list.
- 5c. Now apply one of your favourite list methods to the list. (eg Len, sort, [0]…..)
- """
- """
- file = open("my_new_names_file.txt","a") # a append, r - read only, w - write
- name = ""
- while name != "xxx":
- name = input("Enter a name >> ")
- if name != "xxx":
- file.write(name + "\n")
- file.close()
- """
- # read a file in
- file = open("my_new_names_file.txt","r")
- my_list = file.readlines() # read all in, readline - one at a time, readlines - all in as a list
- file.close()
- print(my_list)
- #loop through
- for each in my_list:
- print(each[:len(each)-1])
- #make_new_list
- my_new_list = []
- for each in my_list:
- my_new_list.append(each[:len(each)-1])
- print(my_new_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement