【发布时间】:2016-03-28 16:00:03
【问题描述】:
我正在尝试在很多文件中查找特定字符串。例如,我正在查找目录和子目录中包含字符串“hello”的文件。
假设我的目录系统如下所示:Dir1 中的 File1 和 File3 包含字符串“hello”,而 File2 不包含。在 Dir2 File1 中包含字符串“hello”。
MainDir:
-> Dir1
-> SubDir1
->File1
->File2
-> SubDir2
->File3
-> Dir2
->SubDir1
->File1
->SubDir1.1
->SubDir1.1.1
-> File1
-> File2
我的代码:
path = "C:\MainDir" #I also get error if I write C:\MainDir\Dir2\SubDir1
word = "hello"
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith(".txt"):
with open(os.path.join(path, name)) as fle:
my_files_content = fle.read()
if word in my_files_content:
print fle.name
如果我写完整路径 if 会找到包含字符串“hello”的文件(例如:path = "C:\MainDir\SubDir1" or C:\MainDir\Dir2\SubDir1.1\SubDir1.1) 但如果我只写我的代码中的路径,它会给我一个错误 “否这样的文件或目录:"
【问题讨论】:
-
不确定您是否直接复制并粘贴了您的代码,但您的路径名中缺少结束
"。 -
我怀疑你直接写了
"c:\foo\bar.txt"之类的东西,并将\f和\b解释为转义序列。您可以复制反斜杠 ("c:\\foo\\bar.txt") 或使用原始字符串 (r"c:\foo\bar.txt") 来避免这种情况。 -
我不认为这是问题所在。代码无法进入子目录并在其中查找文件。
标签: python