Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
自动更改python文件并使用不同的文件名保存_Python_Python 2.7_Automation - Fatal编程技术网

自动更改python文件并使用不同的文件名保存

自动更改python文件并使用不同的文件名保存,python,python-2.7,automation,Python,Python 2.7,Automation,我有一个名为file_1.py的python文件 it has some code in which, i just have to change a word "file_1" to "file_2" 并保留其他函数的缩进` and save it as file_2.py word file_1有3种情况 i have to do this for 100 such times. `file_1.py, file_2.py.....file_100.py` 有没有办法自动执行此操作?运

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

it has some code in which, i just have to change a word "file_1" to "file_2"
并保留其他函数的缩进`

and save it as file_2.py
word file_1有3种情况

i have to do this for 100 such times. `file_1.py, file_2.py.....file_100.py`
有没有办法自动执行此操作?

运行此脚本:

import fileinput

with fileinput.FileInput('file_1.py', inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace('file_1', 'file_2'), end='')
希望获得以下帮助:)

创建脚本:

第一:读取文件

with open("./file1.py") as f:
    content = f.read()
第二:替换文件名

new_content = content.replace("file1","file2")
第三:写新文件(我建议你写一个新文件)

如果您有多个文件,请使用

filenames = ["file" + str(item) for item in range(1,100)]
for filename in filenames:
    with open(filename + ".py") as f:
        content = f.read()
    new_filename = filename[:-1] + str(int(filename[-1]) + 1)
    new_content = content.replace(filename,new_filename)
    with open("./another_folder" + new_filename + ".py", "w") as f:
        f.write(new_content)

是的,有一种方法可以实现自动化:编写代码加载文件,修改内容并用新名称保存文件。是否会出现“file_1”一词?@mpf82是的,先生,对于.txt,它是可用的,但我也必须保留缩进,因为它是python文件。这似乎是一种奇怪的方式。您是否可以更改文件_1.py中的代码,使其使用“文件_1”作为输入,然后维护一个使用不同输入的.py脚本文件?@RajDamani有三种情况,即文件_1didn不理解代码的最后一行
filenames=[“文件”+str(item)用于范围(1100)中的item)]
如何循环?
filenames = ["file" + str(item) for item in range(1,100)]
for filename in filenames:
    with open(filename + ".py") as f:
        content = f.read()
    new_filename = filename[:-1] + str(int(filename[-1]) + 1)
    new_content = content.replace(filename,new_filename)
    with open("./another_folder" + new_filename + ".py", "w") as f:
        f.write(new_content)