我正在处理将在python中打印出文本文件内容的代码。
除了我的最后一行之外,一切似乎都很稳定:
f2 = open('D:\\1CP0_02_June 2016_Paper - Copy\\paintingJobs.txt','r')
for lineB in f2:
if "A" in lineB:
listB = [lineB]
print("Estimate Number\tEstimate Date\tCustomer ID\tFinal Total\tAmount Paid\tAmount Outstanding")
print(listB[0]\tlistB[1]\tlistB[2]\tlistB[3]\tlistB[4]\tlistB[5])
最后一行在执行过程中会产生错误,并说出“线条字符后面的意外字符”'
任何提示?
listB
内有以下内容(仅供澄清):
['E5342,21/09/2015,C103,290,A,290\n']
['E5344,22/09/2015,C105,180,A,180\n']
['E5345,22/09/2015,C106,815,A,400\n']
['E5348,23/09/2015,C109,370,A,200\n']
['E5349,25/09/2015,C110,480,A,250\n']
['E5350,25/09/2015,C111,330,A,330\n']
['E5353,28/09/2015,C114,272,A,200\n']
['E5355,29/09/2015,C116,530,A,450\n']
['E5358,29/09/2015,C119,380,A,380\n']
['E5361,01/10/2015,C122,374,A,374\n']
['E5363,01/10/2015,C124,930,A,500\n']
['E5364,02/10/2015,C125,915,A,800\n']
['E5365,02/10/2015,C126,1486,A,1486\n']
['E5367,03/10/2015,C128,427,A,350\n']
['E5368,05/10/2015,C129,1346,A,1346\n']
['E5371,10/10/2015,C132,289,A,289\n']
['E5373,10/10/2015,C134,1023,A,550\n']
['E5376,13/10/2015,C137,297,A,297\n']
['E5380,15/10/2015,C141,425,A,425']
答案 0 :(得分:4)
print(listB[0]\tlistB[1]\tlistB[2]\tlistB[3]\tlistB[4]\tlistB[5])
这是什么?看起来你想要打印制表符,但你不能只是在某个地方贴上一个制表符来打印它,它必须是一个字符串:
print("{}\t{}\t{}\t{}\t{}\t{}".format(*listB[:6])
但是加入字符串可能更容易:
print("\t".join(listB))
答案 1 :(得分:0)
也许在最后一行尝试这样的事情。
print(listB[0], "\t", listB[1], "\t", listB[2], "\t", listB[3],
"\t", listB[4], "\t", listB[5])
答案 2 :(得分:0)
根据更新问题更新了我的答案:
您不需要在列表中包含此数据:
['E5342,21/09/2015,C103,290,A,290\n']
最好将它作为一个字符串(因为它在列表中的字符串,它没有任何意义)
所以,如果你的listB像这样:
['E5342,21/09/2015,C103,290,A,290\n', 'E5344,22/09/2015,C105,180,A,180\n', 'E5345,22/09/2015,C106,815,A,400\n', 'E5348,23/09/2015,C109,370,A,200\n', 'E5349,25/09/2015,C110,480,A,250\n', 'E5350,25/09/2015,C111,330,A,330\n', 'E5353,28/09/2015,C114,272,A,200\n']
您应该以下一种方式打印数据:
for item in listB:
print("Estimate Number: {0}\tEstimate Date: {1}\tCustomer ID: {2}\tFinal Total: {3}\tAmount Paid: {4}\tAmount Outstanding: {5}".format(*item.strip().split(','))
答案 3 :(得分:0)
使用上面的代码,listB
将只包含文件的最后一行,因为您为每次迭代分配[lineB]
而不是附加它。
另外,如果" A"恰好出现在字符串的第五个字段以外的任何地方,例如在估算编号或客户ID中,它也将包含在listB
中,即使已支付的金额不是" A"。
这个怎么样?
listB = []
with open("d:/filename.txt") as f2:
for lineB in f2:
if "A" == lineB.split(',')[4]:
listB.append(lineB.replace(',','\t').rstrip('\n'))
print("Estimate Number\tEstimate Date\tCustomer ID\tFinal Total\tAmount Paid\tAmount Outstanding")
print("\n".join(listB))