2024-04-19 06:00:10 发布
网友
我有一个名为^{的python文件
it has some code in which, i just have to change a word "file_1" to "file_2"
并保留其他函数的缩进
word file_1有3次出现
有什么方法可以自动化吗?在
创建脚本:
第一:读取文件
with open("./file1.py") as f: content = f.read()
第二个:替换文件名
第三:写新文件(我建议你写一个新文件)
with open("./file2.py", "w") as f: f.write(new_content)
如果您有多个文件,请使用类似
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)
运行此脚本:
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='')
希望这个帮助:)
创建脚本:
第一:读取文件
第二个:替换文件名
^{pr2}$第三:写新文件(我建议你写一个新文件)
如果您有多个文件,请使用类似
运行此脚本:
希望这个帮助:)
相关问题 更多 >
编程相关推荐