python 3:替换文件中的文本

时间:2017-08-28 18:05:28

标签: python-3.x

我有一个文件city.py,我想在下面做两件事:

1.copy city.pynewyork.pylosangeles.py

2. city中有一个单词city.py,我想将其替换为newyorklosangeles

我写了一个文件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可以成功复制,但文件citynewyork.py中的losangeles.py字词无法替换。为什么?

1 个答案:

答案 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()