【发布时间】:2018-12-18 05:18:47
【问题描述】:
我目前正在编写一个脚本来筛选文件系统(Linux 和 Windows),以搜索文本文件中的特定字符串。使用下面的内容,我可以选择我想从哪里开始,获取带有我想要的扩展名的文件的完整路径,但是 stringstofind 似乎没有正确迭代。我最终会将其设置为可以选择要搜索的文件扩展名,并输入我要查找的字符串,但是现在,我只需要它来工作,这样我就可以理解我做错了什么。提前致谢!
目前为止:
import os
userinput = input("What directory to search?")
stringstofind = ["String1", "String2", "String3"]
for roots,subdir, files in os.walk(userinput):
for fname in files:
#I know this if line is ugly, but like with stringstofind I had a hard
#time getting it to iterate through right.
if ".txt" in fname or ".rtf" in fname or ".doc" in fname:
filepath = os.path.join(roots,fname)
with open(filepath, 'r') as f:
for lines in f:
if stringstofind in lines:
print("found target")
【问题讨论】:
-
这实际上应该产生一个错误,如果是这样,那么你应该edit你的问题,以便它包含实际的错误消息。
标签: python directory os.walk python-os