我目前正在编写一个脚本来筛选文件系统(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")
而不是
用途:
我觉得只是有点类型不匹配:
for lines in f:
循环产生的每个lines
变量实际上都是一个字符串stringstofind
被定义为一个列表您正在尝试执行
if stringstofind in lines:
检查字符串列表是否在字符串中。你知道吗您可能的意思是检查} 来实现:
stringstofind
列表中定义的任何字符串是否是行的一部分。您可以使用^{相关问题 更多 >
编程相关推荐