从.txt文件读取并以表格形式打印

时间:2016-02-14 09:39:37

标签: python python-3.x tabular

那么我如何操作一段代码,使其从.txt文件中读取并以表格形式打印数据,其标题为“居民号码”等。 '租赁日期' '价格'等等。?该文件的名称是Residents.txt

到目前为止,我有这个

file = open('Residents.txt','r')
For line in file:
    SplitFile = line.split (',')

这是.txt文件 -
R1,21 / 09/2015,C1,440,P,0
R2,21 / 09/2015,C3,290,A,290
R3,21 / 09/2015,C4,730,N,0
R4,22 / 09/2015,C5,180,A,180
R5,22 / 09/2015,C6,815,A,400
R6,23 / 09/2015,C7,970,N,0
R7,23 / 09/2015,C8,1050,P,0
R8,23 / 09/2015,C9,370,A,200
R9,25 / 09/2015,C10,480,A,250
R10,25 / 09/2015,C11,330,A,330

这是.txt文件中每列的表示 -

line.split[0] = Resident Number      
line.split[1] = Rent Date       
line.split[2] = Customer number        
line.split[3] = Rent amount         
line.split[4] = (A means Accepted)(N means not accepted)(P means Pending)          
line.split[5] = Amount paid    

请注意 -
如果支付的金额等于租金金额,居民数据不应显示在表格中 如果状态为N或P,那么居民数据也不应显示在表格中

如何显示一个表格(没有导入模块),其标题为“居民号”' '租赁日期' '客户编号' '租金金额' '未付金额' - 未付金额仅为租金金额 - 从该行支付的金额。此外,我如何打印未付款项的最终总额(对于尚未支付状态为“A'”的每个人的合计总数)

Python 3.5

谢谢

修改

for i, word in enumerate(line):
        if i == 4 :  # We don't print the status
            continue
        elif i == 2:
            continue
        print(word.ljust(len(headers[i - (i > 4)(i > 2)])), end="    " * ((i - (i > 4)(i > 2)) != len(headers) - 1))
print()

进一步编辑(15/02)

line = line.strip().split(",")
    subtotal = int(line[3]) - int(line[5])
    line.append(str(subtotal))
    if line[5] == line[3] or line[4] in ("N", "E"):
        continue
    total += subtotal

2 个答案:

答案 0 :(得分:-1)

您可以使用制表

https://pypi.python.org/pypi/tabulate

来自链接:

from tabulate import tabulate

table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
        ["Moon",1737,73.5],["Mars",3390,641.85]]
print tabulate(table)

输出:

-----  ------  -------------
Sun    696000     1.9891e+09
Earth    6371  5973.6
Moon     1737    73.5
Mars     3390   641.85
-----  ------  -------------

答案 1 :(得分:-1)

你可以这样做:

headers = ["Resident Number", "Rent Date", "Customer number", "Rent ammount", "Ammount paid", "Outstanding Ammount"]

print("    ".join(headers))
for line in open("test.txt", "r"):
    line = line.strip().split(",")
    line.append(str(int(line[3]) - int(line[5])))
    if line[5] == line[3] or line[4] in ("N", "P"):
        continue
    for i, word in enumerate(line):
        if i == 4:
            continue
        print(word.ljust(len(headers[i - (i > 4)])), end="    " * ((i - (i > 4)) != len(headers) - 1))
    print()

输出:

Resident Number    Rent Date    Customer number    Rent ammount    Ammount paid    Outstanding Ammount
R5                 22/09/2015    C6                 815             400             415                
R8                 23/09/2015    C9                 370             200             170                
R9                 25/09/2015    C10                480             250             230