Python-递归查找和替换文本文件中字符串的方法

2024-09-28 23:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想递归地搜索包含文本文件子目录的目录,并用多行字符串的内容替换文件中每次出现的{$replace}。如何用python实现这一点?

[编辑]

到目前为止,我所拥有的只是使用os.walk获取需要更改的文件列表的递归代码。

import os
import sys
fileList = []
rootdir = "C:\\test"
for root, subFolders, files in os.walk(rootdir):
  if subFolders != ".svn":
    for file in files:
      fileParts = file.split('.')
      if len(fileParts) > 1:
        if fileParts[1] == "php":
          fileList.append(os.path.join(root,file))


print fileList

Tags: 文件inimportforifosrootfiles
3条回答

签出os.walk

import os
replacement = """some
multi-line string"""
for dname, dirs, files in os.walk("some_dir"):
    for fname in files:
        fpath = os.path.join(dname, fname)
        with open(fpath) as f:
            s = f.read()
        s = s.replace("{$replace}", replacement)
        with open(fpath, "w") as f:
            f.write(s)

上面的解决方案有缺陷,比如它打开了它找到的每个文件,或者每个文件都被完全读入内存(如果你有一个1GB的文本文件,这会很糟糕),但是它应该是一个很好的起点。

如果您希望执行比查找特定字符串更复杂的查找/替换,则还可能需要查看re module

对于那些使用Python 3.5+的用户,现在可以使用**recursive标志递归地使用glob

下面是一个将所有.txt文件的hello替换为world的示例:

for filepath in glob.iglob('./**/*.txt', recursive=True):
    with open(filepath) as file:
        s = file.read()
    s = s.replace('hello', 'world')
    with open(filepath, "w") as file:
        file.write(s)

步行很好。但是,看起来您需要对文件类型进行文件管理(如果您要遍历某个目录,我建议您这样做)。为此,您应该添加import fnmatch

import os, fnmatch
def findReplace(directory, find, replace, filePattern):
    for path, dirs, files in os.walk(os.path.abspath(directory)):
        for filename in fnmatch.filter(files, filePattern):
            filepath = os.path.join(path, filename)
            with open(filepath) as f:
                s = f.read()
            s = s.replace(find, replace)
            with open(filepath, "w") as f:
                f.write(s)

这允许您执行以下操作:

findReplace("some_dir", "find this", "replace with this", "*.txt")

相关问题 更多 >