Advertisement
jspill

webinar-files-2023-05-13

May 13th, 2023 (edited)
1,210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. # Files 2023 5 13
  2.  
  3. # FILES!!!
  4.  
  5. # Ch 14 Labs to 100%, watch Submit Mode unit tests
  6. # file questions on Prac Tests, Ch 33-34, and the Pre
  7. # Ch 31 do at least 31.2 (I called this 32.2 today... I meant 31.2, the movie show times Lab)
  8.  
  9. # create a file object
  10. # ... with the open()
  11. # we get access to file object methods: read(), readlines(), write()
  12.  
  13. # MODES
  14. # READ
  15. # WRITE
  16. # APPEND
  17.  
  18. # READ MODE
  19. # filename = input()
  20. with open("test.txt", "r") as f:
  21.     contents = f.readlines() # list of strings, line by line
  22.  
  23. print(contents) # ['Hello.\n', 'This\n', 'is\n', 'just\n', 'a\n', 'string.\n', 'But...\n', 'with\n', 'many\n', 'line\n', 'breaks!']
  24.  
  25. # for line in contents:
  26. #     print(line) # one /n in the string itself, and another from print()
  27.  
  28. # for line in contents:
  29. #     line = line.strip()
  30. #     print(line)
  31.  
  32. # CSV Module
  33. # reader() method
  34. import csv
  35. with open("mock_data.csv", "r") as f1:
  36.     # contents = f.readlines()  # list of strings, line by line
  37.     contents = list(csv.reader(f1)) # for tsv files csv.reader(f1, delimiter="\t")
  38. # print(contents) # a list of lists... [['id', 'first_name', 'last_name', 'email', 'gender', 'ip_address'], ['1', 'Remington', 'Shilling', 'rshilling0@wsj.com', 'Male', '1.71.141.52']...
  39. # for row in contents[0:20]:
  40. #     print(row)
  41.  
  42. # WRITE MODE
  43. with open("output_data3.csv", "w") as f2:
  44.     # write a new csv with rows from this one where last name starts with R
  45.     for row in contents:
  46.         # last name is position 2 of inner list: row[2]
  47.         if row[2][0] == "R": # if row[2][0].lower() == "r": # if row[2].startswith("R"):
  48.             # take action! Write to the new file
  49.             f2.write(",".join(row)+"\n") # write() method takes one single str argument
  50.  
  51. # APPEND MODE
  52. # "Let's write one more row onto the end of that previous file
  53. # ['1', 'Remington', 'Shilling', 'rshilling0@wsj.com', 'Male', '1.71.141.52']
  54. with open("output_data3.csv", "a") as f2:
  55.     f2.write("1001,Shilling,Remington,sremington@wsj.com,Male,1.71.141.53\n")
  56.  
  57.  
  58.  
  59. # You can get mock data like the kind in my first csv:
  60. # www.mockaroo.com
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement