我试图从每一行添加它们但它不起作用
import csv
FILE_NAME = "paintingJobs.txt" #I use this so that the file can be used easier
COL_HEADERS = ['Number', 'Date', 'ID', 'Total', 'Status', 'Paid']
NUM_COLS = len(COL_HEADERS)#This will insure that the header of each column fits into the length of the data
# read file once to determine maximum width of data in columns
with open(FILE_NAME) as f:
reader = csv.reader(f, delimiter=',')
# determine the maximum width of the data in each column
max_col_widths = [len(col_header) for col_header in COL_HEADERS]
for columns in reader:
for i, col in enumerate(columns):
if "A" in columns and int(columns[5]) < int(columns[3]):
max_col_widths[i] = max(max_col_widths[i], len(repr(col)))
# add 1 to each for commas
max_col_widths = [col_width+1 for col_width in max_col_widths]
# read file second time to display its contents with the headers
with open(FILE_NAME) as f:
reader = csv.reader(f, delimiter=',')
# display justified column headers
print(' ' + ' '.join(col_header.ljust(max_col_widths[i])
for i, col_header in enumerate(COL_HEADERS)))
# display justified column data
for columns in reader:
if "A" in columns and int(columns[5]) < int(columns[3]):
print(columns)
print ("Amount_Outstanding:"),
print (int(columns[3]) - int(columns[5])),
这是结果:
Number Date ID Total Status Paid
['E5345', '22/09/2015', 'C106', '815', 'A', '400']
Amount_Outstanding:
415
['E5348', '23/09/2015', 'C109', '370', 'A', '200']
Amount_Outstanding:
170
['E5349', '25/09/2015', 'C110', '480', 'A', '250']
Amount_Outstanding:
230
['E5353', '28/09/2015', 'C114', '272', 'A', '200']
Amount_Outstanding:
72
['E5355', '29/09/2015', 'C116', '530', 'A', '450']
Amount_Outstanding:
80
['E5363', '01/10/2015', 'C124', '930', 'A', '500']
Amount_Outstanding:
430
['E5364', '02/10/2015', 'C125', '915', 'A', '800']
Amount_Outstanding:
115
['E5367', '03/10/2015', 'C128', '427', 'A', '350']
Amount_Outstanding:
77
['E5373', '10/10/2015', 'C134', '1023', 'A', '550']
Amount_Outstanding:
473
所以我想知道我是否可以将每个Amount_Outstanding的总数加起来并将其更改为另一个变量,记住我是python和csv的新手
答案 0 :(得分:1)
您可以通过创建&#39; outstanding_amount&#39;来解决此问题。列表,您可以在其中输入所有未付金额并获胜:D
#build the list
outstanding_amount = []
# read file second time to display its contents with the headers
with open(FILE_NAME) as f:
reader = csv.reader(f, delimiter=',')
# display justified column headers
print(' ' + ' '.join(col_header.ljust(max_col_widths[i])
for i, col_header in enumerate(COL_HEADERS)))
# display justified column data
for columns in reader:
if "A" in columns and int(columns[5]) < int(columns[3]):
print(columns)
print ("Amount_Outstanding:")
print (int(columns[3]) - int(columns[5]))
###### NEW PART ######
outstanding_amount.append(int(columns[3]) - int(columns[5]))
# Show the sum of all collected outstanding amount
print (sum(outstanding_amount))
您甚至可以通过执行此类操作来访问数据集。
例如,如果您想知道第二项的未付金额。然后你做:
print outstanding_amount[1] # Since we start from 0, the second item is at index 1