使用Python和os.步行寻找目标

2024-04-26 04:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一个脚本来筛选文件系统(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")

Tags: or文件to字符串inforifos
2条回答

而不是

if stringstofind in lines:
    print("found target")

用途:

for string in stringstofind:
    if string in lines:
        print("found target")

我觉得只是有点类型不匹配:

  • for lines in f:循环产生的每个lines变量实际上都是一个字符串
  • stringstofind被定义为一个列表

您正在尝试执行if stringstofind in lines:检查字符串列表是否在字符串中。你知道吗


您可能的意思是检查stringstofind列表中定义的任何字符串是否是行的一部分。您可以使用^{}来实现:

for line in f:
   if any(item in line for item in stringstofind):
      print("found target")

相关问题 更多 >