我有一个文件city.py
,我想在下面做两件事:
1.copy city.py
为newyork.py
和losangeles.py
。
2. city
中有一个单词city.py
,我想将其替换为newyork
和losangeles
。
我写了一个文件copy_city.py
来执行此操作:
import shutil
def copy_city():
cities = ['newyork', 'losangeles']
for c in cities:
city_file_name = c +'.py'
shutil.copyfile('city.py',city_file_name)
with open(city_file_name, "r+") as f:
read_data = f.read()
read_data.replace('city', c)
if __name__ == "__main__":
copy_city()
问题:
文件city.py
可以成功复制,但文件city
和newyork.py
中的losangeles.py
字词无法替换。为什么?
答案 0 :(得分:0)
我使用了这个answer about reading and writing contents to the same file
import shutil
def copy_city():
cities = ['newyork', 'losangeles']
for c in cities:
city_file_name = c +'.py'
line = ''
shutil.copyfile('city.py',city_file_name)
with open(city_file_name, "r") as f:
read_data = f.read()
line = read_data.replace('city', c)
f.close()
with open(city_file_name, "w") as f:
f.write(line)
f.close()
if __name__ == "__main__":
copy_city()