Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Files 2023 5 13
- # FILES!!!
- # Ch 14 Labs to 100%, watch Submit Mode unit tests
- # file questions on Prac Tests, Ch 33-34, and the Pre
- # Ch 31 do at least 31.2 (I called this 32.2 today... I meant 31.2, the movie show times Lab)
- # create a file object
- # ... with the open()
- # we get access to file object methods: read(), readlines(), write()
- # MODES
- # READ
- # WRITE
- # APPEND
- # READ MODE
- # filename = input()
- with open("test.txt", "r") as f:
- contents = f.readlines() # list of strings, line by line
- print(contents) # ['Hello.\n', 'This\n', 'is\n', 'just\n', 'a\n', 'string.\n', 'But...\n', 'with\n', 'many\n', 'line\n', 'breaks!']
- # for line in contents:
- # print(line) # one /n in the string itself, and another from print()
- # for line in contents:
- # line = line.strip()
- # print(line)
- # CSV Module
- # reader() method
- import csv
- with open("mock_data.csv", "r") as f1:
- # contents = f.readlines() # list of strings, line by line
- contents = list(csv.reader(f1)) # for tsv files csv.reader(f1, delimiter="\t")
- # 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']...
- # for row in contents[0:20]:
- # print(row)
- # WRITE MODE
- with open("output_data3.csv", "w") as f2:
- # write a new csv with rows from this one where last name starts with R
- for row in contents:
- # last name is position 2 of inner list: row[2]
- if row[2][0] == "R": # if row[2][0].lower() == "r": # if row[2].startswith("R"):
- # take action! Write to the new file
- f2.write(",".join(row)+"\n") # write() method takes one single str argument
- # APPEND MODE
- # "Let's write one more row onto the end of that previous file
- # ['1', 'Remington', 'Shilling', 'rshilling0@wsj.com', 'Male', '1.71.141.52']
- with open("output_data3.csv", "a") as f2:
- f2.write("1001,Shilling,Remington,sremington@wsj.com,Male,1.71.141.53\n")
- # You can get mock data like the kind in my first csv:
- # www.mockaroo.com
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement