繁体   English   中英

如何从.txt文件中减去我得到的两个值

[英]How can I subtract two values which I have got from a .txt file

到目前为止,我已经设法在Python中打印出.txt文件的某些部分但是我无法弄清楚如何从我的总金额中减去支付的金额,然后将每列中的未完成值相加。

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)`

这是迄今为止的结果:

 Number   Date          ID      Total   Status  Paid  
['E5345', '22/09/2015', 'C106', '815', 'A', '400']
['E5348', '23/09/2015', 'C109', '370', 'A', '200']
['E5349', '25/09/2015', 'C110', '480', 'A', '250']
['E5353', '28/09/2015', 'C114', '272', 'A', '200']
['E5355', '29/09/2015', 'C116', '530', 'A', '450']
['E5363', '01/10/2015', 'C124', '930', 'A', '500']
['E5364', '02/10/2015', 'C125', '915', 'A', '800']
['E5367', '03/10/2015', 'C128', '427', 'A', '350']
['E5373', '10/10/2015', 'C134', '1023', 'A', '550']

我想要做的是添加一个新列,这是总和和付费的差异

看起来数据存储为字符串。 您是否尝试将它们更改为整数? 你会这样做的。 假设我们有:

x="1"

y="2"

您可以将它们转换为这样的整数。

x=int(x)

y=int(x)

然后你应该没有问题添加它们。

我已经破坏了你的列宽调整方法,但这里只是对文件中最后一个块的简单更改应该做你想要的。 只需在# display justified column data之后替换所有内容。

for row in reader:
    total = int(row[3])
    paid = int(row[5])
    if 'A' in row[4] and paid < total:
        print('\t'.join((_ for _ in row)), total - paid)

使总计和付费金额整数非常简单,找到一种显示新数据的方法更多一些工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM