0

I have a file city.py,I want to do two things below:

1.copy city.py to be newyork.py and losangeles.py.

2.there is a word city in city.py,I want to replace it with newyorkand losangeles.

I write a file copy_city.py to do this:

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

question: The file city.py can be copied successfully,but the word city in file newyork.py and losangeles.py can not be replaced.why is it?

zwl1619
  • 4,002
  • 14
  • 54
  • 110

1 Answers1

0

I used this 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()
tread
  • 10,133
  • 17
  • 95
  • 170