0

I have a txt file containing data that I need to open in a python file and perform a calculation on. A sample of the data file is as follows:

1,22/01/2019,30
2,22/01/2019,40
3,22/01/2019,350
1,23/01/2019,45
2,25/01/2019,10
4,26/01/2019,750
2,29/01/2019,15
1,31/01/2019,50 

I need to create a code that adds together the ending numbers from every line that starts with the number one (as an example it would need to add 30, 45, etc) I have tried using str.strip and it has not been working out please help!

the code I tried was

with open('events.txt') as fn:
    content = fn.readlines()

for line in content:
        if(line.startswith('1')):
            priceUnit=int(str.strip([0:13])) 
4
  • Is this text file all on one line or are there spaces? Commented Mar 11, 2019 at 22:53
  • 1
    please edit and include your try with using str.strip() to show us how it has not been working. Also, have you tried str.strip().split()? Commented Mar 11, 2019 at 22:56
  • I haven't tried str.strip().split() i will try that now thank you Commented Mar 11, 2019 at 22:59
  • 1
    Open the file and iterate over it: for each line; strip whitespace, split on commas, if the first item meets your criteria, accumulate the last item.
    – wwii
    Commented Mar 11, 2019 at 23:01

5 Answers 5

5

You should probably use split() instead:

with open('file.txt', 'r') as f:
    lines = f.readlines()

total = 0
for line in lines:
    if str(line).startswith('1'):
        total += int(line.split(',')[-1])
1
  • @haydeerodriguez if this solved your problem it's common practice to click the check mark by the post so the question is marked solved, and daaawx can get some rep :) Commented Mar 11, 2019 at 23:14
0
unitList = []
total = 0

for line in content:
    values = line.split(",")
    unitList.append(values[2])

for i in values:
    total = total + i

print(total)
1
  • 1
    Please add some explanation to your code. From review.
    – Wai Ha Lee
    Commented Mar 12, 2019 at 0:05
0
with open('events.txt') as fn:
      content = fn.readlines()

final_price = 0
for line in content:
    line = line.strip().split(",")
    if line[0]=="1":
        priceUnit = int(line[2])
        final_price+=priceUnit

When you read with context manager, with. Everything is string as a datatype. And each line is separated by '\n'. So use both strip() and split() methods.

0

Save it as a CSV because it's already delimited by commas (literally rename the file with a .csv on the end). Then use pandas to open it, then just get the rows based on the value 1 in the first column, then add all your numbers up in the last column.

import pandas as pd

# originally data.txt
df = pd.read_csv('data.csv', header=None)

    0       1        2
-----------------------
0   1   22/01/2019  30
1   2   22/01/2019  40
2   3   22/01/2019  350
3   1   23/01/2019  45
4   2   25/01/2019  10
5   4   26/01/2019  750
6   2   29/01/2019  15
7   1   31/01/2019  50

df1 = df.loc[df[0] == 1]
df1

    0       1       2
0   1   22/01/2019  30
3   1   23/01/2019  45
7   1   31/01/2019  50

total = df1[2].sum()
total
>>> 125
0

Using defaultdict from collections you can create a dictionary and add the values based on the keys

from collections import  defaultdict

d = defaultdict(int)

with open("input.csv") as f:
    for line in f:
        line =  line.split(",")
        d[line[0]] += int(line[2])

which outputsa dict with the added values for each key

defaultdict(int, {'1': 125, '2': 65, '3': 350, '4': 750})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.