基本上我需要在包含产品详细信息的txt文件中写一行,这些详细信息来自我拆分的另一个文本文件。作为数量变量的最终细节是输入的数字。
document = open('Task2.txt', 'r')
strquantity = str(quantity)
for line in document:
the_line = line.split(",")
if the_line[0] == GTIN:
with open("receipt.txt", "a") as receipt:
receipt.write(the_line[0] + "," + the_line[1]+ "," +the_line[2] + "," + strquantity)
document.close()
任务2文件包含:
12345670,spatula,0.99
57954363,car,1000.20
09499997,towel,1.20
数量编号为5,GTIN编号为12345670.它应写入文件的行是:
12345670,spatula,0.99,5
但相反它写道:
12345670,spatula,0.99,
5
(没有行间距(下一行有五行))
为什么要这样做,如何制作它只是写入1行?感谢。
答案 0 :(得分:1)
原因是因为当你读到每一行时,它会在最后有一个换行符。因此,当您调用split
时,最终条目也将包含换行符,因此当您编写the_list[2]
时,它将在此时拆分该行。要解决此问题,请致电strip()
以删除换行符,如下所示:
with open('Task2.txt', 'r') as document, open("receipt.txt", "a") as receipt:
strquantity = str(quantity)
for line in document:
the_line = line.strip().split(",")
if the_line[0] == GTIN:
receipt.write(','.join(the_line[0], the_line[1], the_line[2], strquantity) + '\n')
答案 1 :(得分:0)
你需要在爆炸之前修剪每一行的换行符。
the_line=line.strip()
the_line=the_line.split(",")