Skip to main content
 首页 » 编程设计

python之在python中自动替换字符串

2025年05月04日43think

我有一个名为 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) 

请您参考如下方法:

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

with open("path/to/file_1.py") as f: 
    content = f.read() 
 
<b>for i in range(2,101):</b> 
    new_content = content.replace("file_1","file_<b>%s"%i</b>) 
 
    with open("path/to/file_<b>%s.py"%i</b>, "w") as f: 
        f.write(new_content)

所以在这里你用 i 重复这个过程,范围从 2(包括)到 101(不包括)。并且对于每个这样的 i 你 .replace(..) content 这样 "file1" 被替换为"file_%s"%i(此处字符串上的模 % 表示 %s 将替换为 我).

然后您打开一个文件 "path/to/file_%s.py"%i(同样 %s 被 i 的表示替换) 然后将内容写入该文件。

当然你可以每次迭代都读取file_1的内容,但我假设内容是固定的,所以在程序开始时读取一次会更有效率。