我的代码逐行读取和替换python文本文件有什么问题?(What's wrong with my code to read and replace python text file line

编程入门 行业动态 更新时间:2024-10-27 21:21:30
我的代码逐行读取和替换python文本文件有什么问题?(What's wrong with my code to read and replace python text file line by line? [duplicate])

这个问题在这里已有答案:

在Python 13答案中 搜索并替换文件中的一行

我有一个文本文件。 我想用python v3.6逐行读取文本文件,用子串附加每一行,并用逐行替换现有的行。

更清楚的是,这是原始文本文件;

1,2,3 4,5,6

所需的输出文本文件应如下所示;

appended_text,1,2,3 appended_text,4,5,6

这就是我的代码的样子;

with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline)

我没有得到我想要的东西。 我得到的是在文件末尾附加的大量文本。 如何修改代码? 有没有更好的方法来实现我想要的?

This question already has an answer here:

Search and replace a line in a file in Python 13 answers

I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line.

To be clearer, here is the original text file;

1,2,3 4,5,6

The desired output text file should look like this;

appended_text,1,2,3 appended_text,4,5,6

This is how my code looks like;

with open(filename, 'r+') as myfile: for line in myfile: newline = "appended_text" + "," + line myfile.write(newline)

I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?

最满意答案

在文件中没有“替换现有行”这样的东西。 对于您想要执行的操作,您必须使用修改后的内容编写新文件,然后使用新文件替换旧文件。 示例代码:

with open("old.file") as old, open("new.file", "w") as new: for line in old: line = modify(line.lstrip()) new.write(line + "\n") os.rename("new.file", "old.file")

There's no such thing as "replacing an existing line" in a file. For what you want to do, you have to write a new file with the modified content and then replace the old file with the new one. Example code:

with open("old.file") as old, open("new.file", "w") as new: for line in old: line = modify(line.lstrip()) new.write(line + "\n") os.rename("new.file", "old.file")

更多推荐

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

发布评论

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

>www.elefans.com

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