【问题标题】:Using Python and os.walk to find targets使用 Python 和 os.walk 查找目标
【发布时间】: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


【解决方案1】:

我认为这只是类型不匹配:

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

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


您可能的意思是检查stringstofind 列表中定义的任何字符串是否是一行的一部分。您可以为此使用any()

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

【讨论】:

    【解决方案2】:

    而不是

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

    使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      相关资源
      最近更新 更多