[英]Replacing Values in a Text File
I am reading a text file. 我正在阅读一个文本文件。
One line from the text file looks like this and comes at the very end of the text file: 文本文件中的一行如下所示,并位于文本文件的最后:
</DTS:Executable>
I am using replace("</DTS:Executable>","test from me")
我正在使用
replace("</DTS:Executable>","test from me")
Nothing gets replaced and the text stays as is. 没有任何替换,文字保持原样。
What am I doing wrong? 我究竟做错了什么?
What is the extension of the file ? 文件的扩展名是什么?
Can you try this sed
command : 你可以试试这个
sed
命令:
sed -i 's/original/new/g' file.txt
How about reading the data in list and replacing the last element, like so; 如何读取列表中的数据并替换最后一个元素,就像这样;
with open(fname) as f:
content = f.readlines()
lines = [line.rstrip('\n') for line in file]
lines[-1] = "test from me"
Did this work? 这个工作了吗?
If the file content are not to large then straight forward you can do something like this 如果文件内容不大,则可以直接执行以下操作
with open(filename) as f:
content = f.read()
content = content.replace("<old>", "<new>")
with open(filename, "w") as f:
f.write(content)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.