我想递归地搜索包含文本文件子目录的目录,并用多行字符串的内容替换文件中每次出现的{$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
签出os.walk:
上面的解决方案有缺陷,比如它打开了它找到的每个文件,或者每个文件都被完全读入内存(如果你有一个1GB的文本文件,这会很糟糕),但是它应该是一个很好的起点。
如果您希望执行比查找特定字符串更复杂的查找/替换,则还可能需要查看re module。
对于那些使用Python 3.5+的用户,现在可以使用
**
和recursive
标志递归地使用glob。下面是一个将所有
.txt
文件的hello
替换为world
的示例:步行很好。但是,看起来您需要对文件类型进行文件管理(如果您要遍历某个目录,我建议您这样做)。为此,您应该添加
import fnmatch
。这允许您执行以下操作:
相关问题 更多 >
编程相关推荐