I have .csv file looking like this: https://gyazo.com/746719669f079b0b0c22965b63e52910, I have to open this file and proccess data few million times, my code was working with with open() as f: but then I realized it might be super slow since it opens file every time, so I tried to put that data into variable and just use it later, problem is data disappears after first read, here is my code:
import csv
TEST = open("C:/Users/Krzysztof/Documents/SO.csv")
CCSSVV = csv.DictReader(TEST, delimiter=";")
def printdate(FILE):
print("start")
for LINE in FILE:
print(LINE["MATCH DATE"])
print("end")
printdate(CCSSVV)
printdate(CCSSVV)
printdate(CCSSVV)
I wanted output to look like:
start
25.05.2018
25.05.2018
25.05.2018
end
start
25.05.2018
25.05.2018
25.05.2018
end
start
25.05.2018
25.05.2018
25.05.2018
end
but instead it's
start
25.05.2018
25.05.2018
25.05.2018
end
start
end
start
end
csv.DictReaderjust wraps that file object, it's also an iterator of dicts, not a sequence.TEST.seek(0), then re-create just theDictReader. (c)TEST.seek(0), thennext(TEST)to skip the header line, then the existingDictReaderwill continue to work. (d) read the whole iterator of dicts into a sequence in memory, likeCCSSVV = list(CCSSVV), so you can loop over it repeatedly. (e) rewrite your code so it can do everything in a single pass instead of needing three passes.