我有一个文本文件,其中包含https://drive.google.com/file/d/1RwSrIKD_GUZuToP7bRg8fPoG-4ABSLCS/view?usp=sharing之类的数据。这只是一个小例子,但真正的例子非常相似。如何计算总销售额?
我无法对文本文件执行操作。
我想不使用任何图书馆(例如pandas和numpy)来计算总销售额。我只想使用python计算它。 我能够读写文本文件并将其附加到文本文件中,但是我将如何执行一些我没有得到的计算。
f = open("data.txt", "r")
print(f.read())
答案 0 :(得分:1)
您可以通过python完成此操作,而无需使用特殊的库,例如pandas或numpy。 使用文件处理操作和数据结构来处理数据。
考虑您的输入文件,假设您的数据:
Date,SKU,Unit Price,Quantity,Total Price
2019-10-11,name of product1,5,2,10
2019-10-11,name of product2,3,4,12
有关处理,请参见以下示例。
sale = 0 # take a sale variable
with open('test.txt', 'r') as stream:
data = stream.readlines() # get the file content as list
for item in data[1:]: # iterate over list from second line
sale = sale + int(item.split(',')[-1]) # add data from total column
print("Total sale:", sale)
输出:
Total sale: 22
答案 1 :(得分:0)
您提供的示例文件似乎是CSV文件。 Python提供了一个csv库来处理这些(csv)。以下是如何遍历行并计算csv文件中特定列的总和的示例。根据您的需要对其进行修改,您会很方便。
您可以在此处阅读有关csv库的更多信息: https://docs.python.org/3/library/csv.html
`
import csv
filename = 'yourfilename.extension'
total_sales = 0.00
total_rows = 0
with open(filename, 'r') as file:
csvreader = csv.reader(file)
headers = next(csvreader)
salesHeaderIndex = 4 # from the example the index of Total Price Column
for row in csvreader:
total_sales += float(row[salesHeaderIndex])
total_rows += 1
print("Total ", total_sales, total_rows)`