I have this large csv file called myfile.csv. I have a function that counts the number of rows.
Then it calls another function which should do the same thing, but it doesn't output the same results.
The file:
import csv
def main():
csvfile = open('myfile.csv', 'r')
reader = csv.DictReader(csvfile)
mycount = myfunc(reader)
def myfunc(reader):
print "FIRST: " + str(reader)
count = 0
for row in reader:
count = count + 1
print "ONE: " + str(count)
myfunc_two(reader)
def myfunc_two(reader):
print "SECOND: " + str(reader)
count = 0
for row in reader:
count = count + 1
print "TWO: " + str(count)
if __name__ == '__main__':
main()
The output:
FIRST: <csv.DictReader instance at 0xb7240a8c>
ONE: 180433
SECOND: <csv.DictReader instance at 0xb7240a8c>
TWO: 0
Why is the file suddenly empty in myfunc_two?
EDIT 1: Given that the read cursor is at the end of the file, myfunc_two is returning a zero.
But, since myfunc_two does not have the ability to call csvfile.seek(0), can this problem only be solved by passing csvfile to both functions?
NOTE: reader.seek(0) does not work
EDIT 2 : This code below worked while keeping the same idea that the code above was working with, it is not written as an answer because I can't offer a clear explanation to go along with it.
import csv
def main():
file_contents = []
with open('flights_table_all.csv', 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
file_contents.append(row)
leaders = myfunc(file_contents)
def myfunc(reader):
count = 0
for row in reader:
count = count + 1
print "ONE: " + str(count)
myfunc_two(reader)
def myfunc_two(reader):
count = 0
for row in reader:
count = count + 1
print "TWO: " + str(count)
if __name__ == '__main__':
main()