【问题标题】:Output keeps repeating numerous times when creating table from text file从文本文件创建表格时输出不断重复
【发布时间】:2016-08-17 02:50:01
【问题描述】:

我在使用文本文件中的值创建表时遇到了一些问题。我的文本文件如下所示:

e432,6/5/3,6962,c8429,A,4324
e340,2/3/5,566623,c1210,A,3201
e4202,6/5/3,4232,c8419,E,4232
e3230,2/3/5,66632,c1120,A,53204
e4202,6/5/3,61962,c8429,A,4322

我想生成一个包含数组的表,其中:最后一列(支付金额)的值小于第三列的(最终总计),并且如果第五列的(状态)等于“A”。减去最终总额和支付金额后,即可找到未结总额。

我生成表格的代码是:

data = open("pJoptionc.txt", "r")
info=data.readlines()
data.close
for li in info:
        status=li.split(",")[4]
        finaltotal=int(li.split(",")[2])
        amountpaid=int(li.split(",")[5])
        totalrev=0
        headers = ["Estimate Number", "Date", "Final Total", "Customer Number", "Status", "Amount Paid", "Outstanding Amount"]
        print("    ".join(headers))
        for line in open("pJoptionc.txt", "r"):
            line = line.strip().split(",")
            line.append(str(int(line[2]) - int(line[5])))
            if line[2] == line[5] or line[4] in ("E"):
                continue
            for i, word in enumerate(line):
                print(word.ljust(len(headers[i - (i > 4)])), end="    " * ((i - (i > 4)) != len(headers) - 1))
            print()
            outstandingrev =(finaltotal) - (amountpaid) 
    totalrev += int(outstandingrev)
    print("The total amount of outstanding revenue is...")
    print("£",totalrev)

我想要的输出是

Estimate Number    Date    Final Total    Customer Number    Status    Amount Paid    Outstanding Amount
e432               6/5/3    6962           c8429              A         4324           2638           
e340               2/3/5    566623         c1210              A         3201           563422         
e3230              2/3/5    66632          c1120              A         53204          13428          
e4202              6/5/3    61962          c8429              A         4322           57640          
The total amount of outstanding revenue is...
£ 13428

但是,当我运行代码时,输​​出是一遍又一遍重复的表格,并且未结金额列中有负值。我正在使用 python 3.4.3。

【问题讨论】:

    标签: python python-3.x text input output


    【解决方案1】:

    您在循环中再次读取文件,因此它会针对您在表中的每一行重复。尝试这样做: (注意这次文件行只有1个for循环)

    headers = ["Estimate Number", "Date", "Final Total", "Customer Number", "Status", "Amount Paid", "Outstanding Amount"]
    print("    ".join(headers))
    data = open("pJoptionc.txt", "r")
    info=data.readlines()
    data.close()
    totalrev=0
    for li in info:
        line = li.strip().split(",")
        status=line[4]
        finaltotal=int(line[2])
        amountpaid=int(line[5])
    
        line.append(str(int(line[2]) - int(line[5])))
        if line[2] == line[5] or line[4] in ("E"):
            continue
        for i, word in enumerate(line):
            print(word.ljust(len(headers[i - (i > 4)])), end="    " * ((i - (i > 4)) != len(headers) - 1))
        print()
        outstandingrev =(finaltotal) - (amountpaid) 
        totalrev += int(outstandingrev)
    print("The total amount of outstanding revenue is...")
    print("£",totalrev)
    

    **旁注:您可能想查看csv 模块: https://docs.python.org/3/library/csv.html

    【讨论】:

      【解决方案2】:

      表格一遍又一遍地重复,因为您阅读了脚本顶部的文件,然后对于文件中的每一行,您再次重新打开文件。

      这是使用namedtuple的一种方法:

      from collections import namedtuple
      
      # define a named tuple for storing each line (record)
      fields = ['Estimate_Number', 'Date', 'Final_Total', 'Customer_Number', 'Status', 'Amount_Paid']
      record = namedtuple('record', fields)
      
      # first print the header
      for field in fields:
          print('%-17s' % field.replace('_', ' '), end='')
      print('Outstanding')
      
      totalOutstanding = 0
      
      # open the file using a context manager (the with keyword)
      with open("pJoptionc.txt", "r") as data:
      
          for line in data:
      
              # strip the newline character, split on the comma and create a record
              row = record(*line.strip().split(','))
      
              # we can access each field by name now to make the code more readable  
              outstanding = int(row.Final_Total) - int(row.Amount_Paid)
      
              # print the output
              if outstanding:
                  for field in fields:
                      print('%-17s' % getattr(row, field), end='')
                  print(outstanding)
                  totalOutstanding += outstanding
      
      print('Total Outstanding is... %s' % totalOutstanding)
      

      参考资料:

      【讨论】:

        猜你喜欢
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 2023-03-05
        • 2021-08-29
        • 2019-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多