[英]Using python how do I insert a string in select lines of a text file where the inserted string depends on the content of the line and a known mapping?
[英]Python - How to replace a string in a text file where value is not known?
我需要在文本文件行中找到一个字符串并将其替换为 Python 中的新字符串。 问题是文本文件中有很多行,而且需要替换的单词也不知道。 假设文本文件是这样的:
Priminster - 1231 - Johnson - Gary
president - 213 - Stevens - Michael
假设如果“史蒂文”这个词不知道,我想将“史蒂文斯”这个词换成“哈利”。
如果您可以以某种方式在变量中获取unknown string
,那么这可能会有所帮助。 这将用另一个字符串替换一个字符串(如果存在)。
to_be_replaced = "Stevens"
to_be_placed = "Harry"
with open('textfile.txt', 'r') as fr:
old_data = fr.read()
if to_be_replaced in old_data:
new_data = old_data.replace(to_be_replaced, to_be_placed)
with open('textfile.txt', 'w') as fw:
fw.write(new_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.