-1

So I have this problem I need to solve. I have a file that goes something like:

11-08-2012;1485;10184;7,53;31;706;227;29;6;1102

12-08-2012;2531;10272;7,59;25;695;222;26;22;1234

13-08-2012;1800;13418;8,66;46;714;203;50;6;0757

14-08-2012;2009;11237;9,43;81;655;246;49;7;1783

And I should be able to read the "1485" and then the "2531" part and then the "1800" part and go all the way to the end of the file and finally sum them up. How do I do that? I wrote under this text how I tried to approach this problem with while. But I seem to be lost with this one. Anyone can help?

while True:

    f.seek(12)
    text=f.read(4)

    text=f.readline()
    if(text==""):
        break
    return text
cosman
  • 23
  • 5

4 Answers4

1

There are number of ways to do this, with numpy, pandas, simple coroutines and so on. I am adding the one closest to your approach.

total = 0
with open('exmplefile.txt','r') as f:
    for line in f:
        elements = line.split(';')
        num_of_interest = int(elements[1])
        # you can add a print if you want
        total += num_of_interest
print(total)
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
1

This solution is by getting the first and second index of a common term, in this case ;.

with open(filename,'r') as file:
    file_list = file.readlines()

sum = 0

for line in file_list:
    loc = line.find(';')
    first_loc = loc + 1
    last_loc = loc +line[loc+1:].find(';')+1

    sum = sum + int(line[first_loc:last_loc])

print(sum)
noswear
  • 311
  • 1
  • 6
  • 27
0

Try this

mylist = []
for string in file:
    mynum = string.split(';')[1]
    mylist.append(mynum)
sum([int(i) for i in mylist])
ian-campbell
  • 1,605
  • 1
  • 20
  • 42
0

This solution caters for when the 4 digit is not the second item in the array

with open("path/to/file") as f:
  f1 = f.readlines()

  sum = 0
  for line in f1:
    lineInArray = line.split(';')
    for digit in lineInArray:
      if len(digit.strip()) == 4 and digit.strip().isnumeric():
        sum += int(digit)
Nature
  • 149
  • 1
  • 6
  • Cosman, the with syntax is a context manager that ensures the file is closed after opening it for processing its content. For the with line statement in the code, you can replace with ```f = open('path/to/file')``` and un-indent the block. With this style however, you must call ```f.close()``` at the end of the code – Nature Oct 14 '19 at 06:30