0

I am doing some basic stuff with reading files, etc. I am tasked with finding how many lines (records) there are in the file and the total number of incidents (aggregation of one of the columns).

I have figured out both numbers, however, when I put all the code together, I get the sum of one of the criteria and total of 0 for the other. But when I do each criteria separately, I have no problems.

myFile = open("PS3_wnvhumancases.txt", "r")
nincidents = 0
for char in myFile.readlines():
    new_file = char.split(',')
    cases = new_file[-1]
    nincidents += int(cases)
nrecs = len(myFile.readlines())
print('Total Records Processed: ', nrecs)
print('Total Incidents: ', nincidents)
myFile.close()

The code above gives me the correct total of incidents and 0 for total reports

Meanwhile,

myFile = open("PS3_wnvhumancases.txt", "r")
nrecs = len(myFile.readlines())
print('Total Records processed: ', nrecs)
nincidents = 0
for char in myFile.readlines():
    new_splt = char.split(',')
    cases = new_splt[-1]
    nincidents += int(cases)
print('Total Incidents: ', nincidents)
myFile.close()

This block of code gives me the number of reports and 0 for total incidents.

Any suggestion that will give me both numbers?

slick248
  • 1
  • 1
  • This looks like it's because you are calling readlines twice, which will advance the pointer to the end of the file after the first time. Simply assign `myFile.readlines()` to a variable once and use that variable. – Ken Syme Sep 23 '19 at 14:49
  • Related reading: https://stackoverflow.com/q/3906137/953482 – Kevin Sep 23 '19 at 14:50
  • 1
    If you had tried to debug your program, you would have caught the reason before. – Austin Sep 23 '19 at 14:50

1 Answers1

1

You are exhausting the file when you do .readlines(). You would need to seek back to start or just keep the output as a variable like below:

myFile = open("PS3_wnvhumancases.txt", "r")
content = myFile.readlines()
nrecs = len(content)
print('Total Records processed: ', nrecs)
nincidents = 0
for char in content:
    new_splt = char.split(',')
    cases = new_splt[-1]
    nincidents += int(cases)
print('Total Incidents: ', nincidents)
myFile.close()
PyPingu
  • 1,697
  • 1
  • 8
  • 21