尝试在CVS文件中添加列。它们被列为字符串,但是数字,我需要找到总数,但首先转换为整数。
import csv
filename = open('sales.csv','r')
file = csv.DictReader(filename)
sales = []
for col in file:
sales.append(col['sales'])
print(sales)
写了这个,但坚持转换字符串和使用sum函数。
对于这种类型的工作,我建议查看pandas
,但是
import csv
sales = []
with open('sales.csv') as f:
reader = csv.DictReader(f)
for row in reader:
val = float(row['sales']) # convert to a number; use int() if you don't have decimals
sales.append(val)
print(sum(sales))
我建议您考虑将所有数据类型转换作为一个步骤进行,然后再处理数据:
import csv
import decimal # You should generally use decimal instead of float for currency
sales_records = []
with open('sales.csv') as sales_file:
sales_reader = csv.DictReader(sales_file)
for row in sales_reader:
typed_record = {
'label': row['label'], # for example
'sales': int(row['sales']),
'price': decimal.Decimal(row['price']), # for example
}
sales_records.append(typed_record)
sales_total = sum([record['sales'] for record in sales_records])
price_total = sum([record['price'] for record in sales_records])
更新:在下面添加逐行分解:
导入一些我们需要的包:
import csv
import decimal
创建一个空列表来保存记录:
sales_records = []
使用"上下文管理器"打开文件。以确保在我们完成它时它是关闭的(这对我们的计算机和程序的其余部分很好)
with open('sales.csv') as sales_file:
... # everything indented inside this "with" is while the file is open
创建一个CSV阅读器,将文件中的行作为字典而不是一个长字符串提供给我们:
sales_reader = csv.DictReader(sales_file)
遍历文件的行字典,一次一个:
for row in sales_reader:
... # everything here applies to a single row
为每一行创建一个新的字典(称为typed_record)
typed_record = {
... # keys and values for the dictionary here as 'key': value,
}
取一个名为"label"并将其直接放到新字典中:
'label': row['label'],
取一个名为"sales"在本行中,将其转换为int型并将其放入新字典中:
'sales': int(row['sales']),
取一个名为"price"在我们的行中,将其转换为Decimal并将其放入新字典中:
'price': decimal.Decimal(row['price']),
将新字典添加到所有记录列表中:
sales_records.append(typed_record)
最后两行,同时做两件事:
首先,将字典记录列表转换为只有一个值的列表(这称为"列表推导");是一个非常强大的工具:
[record['sales'] for record in sales_records]]
然后,我们把所有这些值加起来:
sales_total=sum(...)