【发布时间】:2018-04-26 07:37:55
【问题描述】:
我想查找字符串,例如我的文件夹文件中的“Version1”包含多个“.c”和“.h”文件,并使用python文件将其替换为“Version2.2.1”。
有人知道这是怎么做到的吗?
【问题讨论】:
标签: python string directory find-replace
我想查找字符串,例如我的文件夹文件中的“Version1”包含多个“.c”和“.h”文件,并使用python文件将其替换为“Version2.2.1”。
有人知道这是怎么做到的吗?
【问题讨论】:
标签: python string directory find-replace
这是一个使用 os、glob 和 ntpath 的解决方案。结果保存在名为“输出”的目录中。你需要把它放在你有 .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)
【讨论】: