在python中自动替换字符串

Shu*_*m R 1 python string replace file

我有一个名为file_1.py的python文件

它有一些代码,我只需更改一个单词:"file_1"到:"file_2"并将其另存为file_2.py,然后再将'file_1'替换为'file_3'并将其另存为 file_3.py

我必须这样做100次,创建100个python文件:file_1.py,file_2.py ...... file_100.py

我编写了一个可以替换字符串的代码,但我仍然坚持编写一个自动化它的循环.任何线索?

with open("path/to/file_1.py") as f:
content = f.read()

new_content = content.replace("file_1","file_2")

with open("path/to/file_2.py", "w") as f:
    f.write(new_content)
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

您可以简单地使用for循环替换和写入:

with open("path/to/file_1.py") as f:
    content = f.read()

for i in range(2,101):
    new_content = content.replace("file_1","file_%s"%i)

    with open("path/to/file_%s.py"%i, "w") as f:
        f.write(new_content)
Run Code Online (Sandbox Code Playgroud)

所以在这里你重复这个过程,i范围从2(包括)到101(不包括).而对于每一个这样的i.replace(..)content这种"file1"被替换"file_%s"%i(模%上的绳子这里指%s将的表现来代替i).

然后打开一个文件"path/to/file_%s.py"%i(再次%s被表示替换i),然后将内容写入该文件.

您当然可以阅读file_1每次迭代的内容,但我认为内容是固定的,因此在程序开头读取一次将更有效.