这个问题在这里已有答案:
在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 answersI 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,6The desired output text file should look like this;
appended_text,1,2,3 appended_text,4,5,6This 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")更多推荐
发布评论