当我只要求它输入1时,为什么写入文本文件中的2行?(Why does it write to 2 lines in a text file when I only ask it to type 1?)

编程入门 行业动态 更新时间:2024-10-28 06:21:56
我只要求它输入1时,为什么写入文本文件中的2行?(Why does it write to 2 lines in a text file when I only ask it to type 1?)

基本上我需要在包含产品详细信息的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.20

The quantity number is 5 and the GTIN number is 12345670. The line it should write to the file is:

12345670,spatula,0.99,5

But 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')

更多推荐

本文发布于:2023-07-28 21:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1309444.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我只   文本文件   write   lines   file

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!