使用 python 从文件夹中的多个文件中查找和替换字符串
find and replace string from multiple files in a folder using python
我想查找字符串,例如"Version1" 从我的文件中提取包含多个“.c”和“.h”文件的文件夹,并使用 python 文件将其替换为 "Version2.2.1"。
有人知道如何做到这一点吗?
这是一个使用 os、glob 和 ntpath 的解决方案。结果保存在名为 "output" 的目录中。你需要把它放在你有 .c 和 .h 文件的目录中,运行 它。
创建一个名为 output 的单独目录,并将编辑后的文件放在那里:
import glob
import ntpath
import os
output_dir = "output"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for f in glob.glob("*.[ch]"):
with open(f, 'r') as inputfile:
with open('%s/%s' % (output_dir, ntpath.basename(f)), 'w') as outputfile:
for line in inputfile:
outputfile.write(line.replace('Version1', 'Version2.2.1'))
替换字符串到位:
重要!请务必在 运行 执行此操作之前备份您的文件:
import glob
for f in glob.glob("*.[ch]"):
with open(f, "r") as inputfile:
newText = inputfile.read().replace('Version1', 'Version2.2.1')
with open(f, "w") as outputfile:
outputfile.write(newText)
我想查找字符串,例如"Version1" 从我的文件中提取包含多个“.c”和“.h”文件的文件夹,并使用 python 文件将其替换为 "Version2.2.1"。
有人知道如何做到这一点吗?
这是一个使用 os、glob 和 ntpath 的解决方案。结果保存在名为 "output" 的目录中。你需要把它放在你有 .c 和 .h 文件的目录中,运行 它。
创建一个名为 output 的单独目录,并将编辑后的文件放在那里:
import glob
import ntpath
import os
output_dir = "output"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for f in glob.glob("*.[ch]"):
with open(f, 'r') as inputfile:
with open('%s/%s' % (output_dir, ntpath.basename(f)), 'w') as outputfile:
for line in inputfile:
outputfile.write(line.replace('Version1', 'Version2.2.1'))
替换字符串到位:
重要!请务必在 运行 执行此操作之前备份您的文件:
import glob
for f in glob.glob("*.[ch]"):
with open(f, "r") as inputfile:
newText = inputfile.read().replace('Version1', 'Version2.2.1')
with open(f, "w") as outputfile:
outputfile.write(newText)