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

标签 python string file replace

我有一个名为 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(同样 %si 的表示替换) 然后将内容写入该文件。

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

关于python - 在python中自动替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343551/

相关文章:

java - 如何将分割数组的其余部分转换为java上的字符串?

c++ - 在编译时加密/混淆字符串文字

c++ - 将字符串作为指针传递时出错,无法将 const char* 分配给 char*

python - 获取 "ValueError: I/O operation on closed file"

c - fscanf 如何处理不同的变量类型?

python - 有没有办法避免这种重复的代码?

python - wxPython:导出位图时的路径问题

python - 使用散列从数据框中删除列

Python:标准函数和上下文管理器?

php - 了解php中下载文件的位置