[英]python : replace mutiple words in a file
我有一个文件apple.py
,它的单词是apple
和Apple
。 并且有一个空白文件pear.py
我想读取apple.py
的内容并将其写入pear.py
并进行修改
apple
对pear
, Apple
对Pear
。
我这样做是这样的:
def modify_city():
with open('city.py', 'r+') as f:
read_data = f.read()
with open('beijing', 'w') as f:
f.write(read_data.replace('city', 'beijing')) #it works
f.write(read_data.replace('City', 'Beijing')) #it doesn't work
题:
在代码中,第一个replace()
有效,但是第二个replace()
不起作用。我该怎么办?
您将整个read_data写入文件两次。
read_data = read_data.replace('city','beijing')
read_data = read_data.replace('City','Beijing')
f.write(read_data)
您的代码无法正常工作的原因是:
str.replace()
返回替换完成的字符串,而不更改原始字符串。 通过做
f.write(read_data.replace('city', 'beijing'))
第一次,您将打印到文件read_data
并替换为'city'
和'beijing'
但没有将更改保存到read_data
。 第二次当你做
f.write(read_data.replace('City', 'Beijing'))
之前的替换未保存,因此导致替换了原始字符串。
话虽这么说,您有两种选择:
def modify_city():
with open('city.py', 'r+') as f:
read_data = f.read()
with open('beijing.py', 'w') as f:
f.write(read_data.replace('city', 'beijing').replace('City', 'Beijing'))
要么
def modify_city():
with open('city.py', 'r+') as f:
read_data = f.read()
read_data = read_data.replace('city', 'beijing')
read_data = read_data.replace('City', 'Beijing')
with open('beijing.py', 'w') as f:
f.write(read_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.