<p>我目前正在编写一个脚本来筛选文件系统(Linux和Windows),在文本文件中搜索特定的字符串。使用下面的内容,我可以选择我想要的开始位置,获得带有我想要的扩展名的文件的完整路径,但是stringstofind似乎没有正确地迭代。我最终会这样做,我可以选择要搜索的文件扩展名,并输入我要找的字符串,但现在,我只需要这个工作,这样我就可以理解我做错了什么。提前谢谢!你知道吗</p>
<p>到目前为止,我已经:</p>
<pre><code>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")
</code></pre>
<p>而不是</p>
<pre><code>if stringstofind in lines:
print("found target")
</code></pre>
<p>用途:</p>
<pre><code>for string in stringstofind:
if string in lines:
print("found target")
</code></pre>