haydee rodriguez
haydee rodriguez

Reputation: 35

Stripping a data file

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])) 

Upvotes: 0

Views: 387

Answers (5)

Daniel
Daniel

Reputation: 5391

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})

Upvotes: 0

Ari
Ari

Reputation: 6199

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

Upvotes: 0

Raviteja Ainampudi
Raviteja Ainampudi

Reputation: 282

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.

Upvotes: 0

daaawx
daaawx

Reputation: 3473

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])

Upvotes: 5

Olufemi Adesina
Olufemi Adesina

Reputation: 129

unitList = []
total = 0

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

for i in values:
    total = total + i

print(total)

Upvotes: 0

Related Questions