如何阅读txt.file并找到不同价格的不同产品的总和

  • 本文关键字:何阅读 txt file python list sum txt
  • 更新时间 :
  • 英文 :


我有以下文本文件products.txt:

产品;数量价格苹果3.10香蕉1.5柠檬2.3橙色4.20苹果4.8.00

我想读取此文件并创建一个新的文本文件newfile.txt,其中包含每行的值(金额X价格):

30.00568032.00

最后,我想找到newfile.txt的总和(即30+5+6+80+32=153)

请注意,同一产品的价格可能会有所不同,我们对每种产品的总价不感兴趣。

我从创建类开始。

class DATA:
product= ""
amount= 0
price= 0

def-read(名称):

list = []
file= open(name, 'r', encoding="UTF-8")
file.readline()
while (True):
row= file.readline()
if(rivi == ''):
break
columns= row[:-1].split(';')
info= DATA()
info.amount= int(columns[1])
info.price= int(columns[2])
info.total = info.amount * info.price
file.append(info)
tiedosto.close()
return list

这应该有效:

def read(name):
total = 0
ori = open(name, 'r', encoding="UTF-8")
row = ori.readline()
dest = open("newfile.txt", 'w', encoding="UTF-8")
row = ori.readline()
while (row != ""):
row = row[:-1].split(';')
res = int(row[1])  * float(row[2])
total += res
dest.write(str(res) + "n")
row = ori.readline()

ori.close()
dest.close()
print(total)
read("products.txt")

一种可能性是使用标准库中的csv

import csv
# fix files' paths
path1 = # file to read
path2 = # file to write
# read data and perform computations
rows_tot = [] 
with open(path1, 'r', newline='', encoding="utf-8") as fd:
reader = csv.DictReader(fd, delimiter=";")
for row in reader:
rows_tot.append(float(row['Amount']) * float(row['Price']))
# total sum
print("Total sum:", int(sum(rows_tot)))
# save to file the new data
with open(path2, 'w', newline='') as fd:
fieldnames = ("AmountXPrice",)
writer = csv.DictWriter(fd, fieldnames=fieldnames)
writer.writeheader()
for value in rows_tot:
writer.writerow({fieldnames[0]: f"{value:.2f}"})

备注:从问题中不清楚各种数据的类型,以防将int改为float或反过来。

最新更新