基本上我需要在包含产品详细信息的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行? 谢谢。
Basically I need to write a line to a txt file containing details about a product, these details are from another text file which I split. The final detail which is the quantity variable is an inputted number.
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()The task 2 file contains:
12345670,spatula,0.99 57954363,car,1000.20 09499997,towel,1.20The quantity number is 5 and the GTIN number is 12345670. The line it should write to the file is:
12345670,spatula,0.99,5But instead it writes:
12345670,spatula,0.99, 5(no line space (five on the next line under))
Why does it do this and how do I make it so it just writes to the 1 line? Thanks.
最满意答案
原因是当你读到每一行时,它会在最后有一个换行符。 因此,当您调用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')The reason is because when you read in each line, it will have a newline at the end. So when you call split, the final entry will also contain a newline, so when you write the_list[2] it will split the line at this point. To get around this, call strip() to remove the newline as follows:
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')更多推荐
发布评论