# Working with Files - Reading and Writing # Sat Feb 12 # opening a file # older syntax # f = open("test.txt", "r") # r, w, a, and r+, w+, a+... don't worry about those # # work with the file # f.close() # newer way, the with/open() block with open("test.txt", "r") as f: # r is default mode, but I'll include # work with file # 2 ways I normally grab the contents of file # read() # returns the entire contents of the file, as one big string # readlines() # returns a list of strings, kinda like str.split() myList = f.readlines() # when you leave the block, the file is closed # in read mode, you might as well close as soon as possible to save memory # I still have myList print(myList) for line in myList:# line here is a str in the list # print(type(line)) # print("Is string?", isinstance(line, str)) # line = line.rstrip() # strip() print(line, end="-") # print(end="\n") # if I want update the list # myList[x] myList[myList.index(line)] = line.rstrip() print() print(myList) print("---------------") # we could use the csv module and its csv.reader() instead import csv # with open("mock_data.csv", "r") as cFile: # myList = cFile.readlines() # # print(myList) # for line in myList: # # line = line.rstrip() # row = line.rstrip().split(",") # print(row[3]) with open("mock_data.csv", "r") as cFile: myVar = csv.reader(cFile, delimiter=",") myVar = list(myVar) # I like to recast a csv.reader file as a list... print(myVar) # Look! It's a LIST of LISTS # with open()... # write() # in "w" mode, destructive; in "a" mode it appends to end # Let's look at the first part of Lab 29.1 filename = input().rstrip() # open in read with open(filename, "r") as f: # myList = f.readlines() myList = [line.rstrip() for line in f.readlines()] # print(myList) # looks good! tvDict = {} # for item in myList: # but range() would be better to get index for i in range(0, len(myList), 2): key = myList[i] # value = myList[i+1] if key in tvDict: # if it's ALREADY in there tvDict[key] += "; {}".format(myList[i + 1]) else: tvDict[key] = myList[i + 1] # so this is the normal thing to do... print(tvDict) # write output_keys.txt with open("output_keys.txt", "w") as f: for k in tvDict: # print("{}: {}\n".format(k, tvDict[k])) # writing looks the same... f.write("{}: {}\n".format(k, tvDict[k])) # it's just strings! # That's MOST of writing out the output_keys.txt file they asked for, but... # In unit testing you will get a curve ball: you have to control for # "zero padded" numbers vs not: "07" vs "7" in your keys # if you're ever reading and writing in the same open() block... f.seek() # moves to position in filestream you're reading/writing, like a scrubber