Advertisement
jspill

webinar-files-2023-04-05

Apr 15th, 2023
1,328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.65 KB | None | 0 0
  1. # Files 2023 4 15
  2.  
  3. # FILES!!!
  4. # READ MODE
  5. # filename = input()
  6. # with open("test.txt", "r") as f:
  7. #     # readlines() is a useful file object method
  8. #     contents = f.readlines() # list of strings, line by line
  9. #
  10. # print(contents)
  11. # print(type(contents).__name__)
  12. # # for loop
  13. # for line in contents:
  14. #     # line = line.strip()
  15. #     print(line, end="") # print(line, end="\n")
  16. # print()
  17.  
  18. # print("This should start on a clean new line!")
  19.  
  20. # CSV Module
  21. import csv # csv module is reader()
  22. with open("mock_data.csv", "r") as f1:
  23.     # contents = f.readlines()  # list of strings, line by line
  24.     contents = list(csv.reader(f1)) # csv.reader(f1, delimiter="\t")
  25. # print(contents[:30])
  26.  
  27. # WRITE MODE
  28. with open("output_data.csv", "w") as f2:
  29.     for row in contents:
  30.         # email is row[3]
  31.         # how to check end of email string? 1) slice 2) str endswith() 3) IN keyword
  32.         if row[3][-4:] == ".gov": # if row[3].endswith(".gov"):
  33.             # print(row) # just checking! Slice is good and data looks good
  34.             # write() method takes one single str argument
  35.             f2.write(",".join(row)+"\n") # is that enough...?
  36.  
  37.  
  38. # for method in dir(str):
  39. #     if not method.startswith("_"):
  40. #         print(f"{method}()")
  41.  
  42. # APPEND MODE
  43. # with open("append_to_this.txt", "r") as f3:
  44. #     contents = f3.readlines()
  45. # print(contents) # ['Frodo\n', 'Sam\n', 'Merry\n']
  46. with open("append_to_this.txt", "a") as f3:
  47.     # f3.write("Pippin\n")
  48.     # f3.write("Aragorn\n")
  49.     # f3.write("Gandalf\n")
  50.     f3.write("Gollum\nGlorfindel\nRosie Cotton\n") # you can call write() multiple times, or just add all those strings together
  51.  
  52.  
  53.  
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement