import csv
csv_file = 'Annual Budget.csv'
txt_file = 'annual_budget.txt'
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
reader = csv.reader(my_input_file)
for row in reader:
my_output_file.write(" ".join(row)+'\n')
data = []
with open(r'annual_budget.txt', 'r') as f:
reader = csv.reader(f)
header = next(reader) # this will yield first row i.e columns
for line in reader:
rowdata = map(float, line)
data.extend(rowdata)
print(sum(data)/len(data))
我正在尝试将CSV文件中的列总和打印为txt文件。我告诉我的代码绕过第一行之后,我首先逐步标记了csv文件。我的文件中的字符串标题)会引发错误,提示它无法将字符串转换为浮点数。
输出:
data.extend(rowdata)
ValueError: could not convert string to float: