【问题标题】:Python-Looping through all files in a folderPython-循环遍历文件夹中的所有文件
【发布时间】:2014-04-24 19:44:21
【问题描述】:

我需要在一个目录中搜索几千个单独的文本文件,看看有多少包含一个字符串。我需要使用python。现在我有以下基本代码适用于一个单独的文件。我不知道下一步:如何遍历目录中每个单独文件的内容。这是我所拥有的:

stringtofind = 'FULL TEXT' #enter something between the ''s 
filetolookin = '2013-04-061.txt' #enter the file you want to search

def countif(isthis, infile):
    count = 0
    if isthis in open(infile).read():
        count = 1+count
        return count
    else:
        return count

print countif(stringtofind, filetolookin)

感谢您的帮助。

【问题讨论】:

    标签: python loops if-statement python-2.x


    【解决方案1】:

    这是使用 python 2.7.x 解决此问题的完整工作脚本

    import sys
    import os
    import re
    
    
    def search_count(str,loc):
        count = 0
        os.chdir(loc)    
        for (thisDir, subsHere, filesHere) in os.walk('.'):
            for filename in filesHere:
                with open(filename,"r") as f:
                    content = f.read()
                    if re.search(str,content):
                        count += 1
        return count
    
    
    if __name__ == "__main__":
        stringtofind = raw_input('Enter text to search: ')
        pathtolookin = raw_input('Enter path to search: ')
    
        if sys.platform[:3] == 'win':
            pathtolookin = pathtolookin.replace('\\','/')
        print search_count(stringtofind,pathtolookin)
    

    【讨论】:

      【解决方案2】:

      最好是使用 glob 模块,提供你要搜索的所有文件或 在一个文件夹/目录中。

      import glob
      icount = 0
      stringtofind = 'FULL TEXT' 
      filetolookin = '2013*.txt' 
      g = glob.glob(filetolookin)
      for f in g: 
          icount = 0
          for j in open(f):
              j.find(stringtofind) >=0:
                  print j
                  icount = icount + 1 
                  # or whatever you want
          print "File: ", f, "count ", icount 
      

      【讨论】:

        【解决方案3】:

        这听起来非常适合在标准库中使用fileinput 模块:

        #!/usr/bin/env python
        
        usage = 'Call this with a search string and a list of files to search'
        
        if __name__ == '__main__':
            import sys, fileinput
            if len(sys.argv) < 3:
                print usage
                sys.exit()
        
            search_string = sys.argv[1]
            count = 0
        
            for line in fileinput.input(sys.argv[2:]):
                if search_string in line:
                    count += 1
        
            print count
        

        【讨论】:

          【解决方案4】:

          os.walk 将允许您递归枚举目录中的文件。获得文件名后,如果需要对其进行过滤,请使用 os.path 中的函数来获取文件名和扩展名。对于文件内容,re 模块将允许您使用正则表达式逐行搜索模式。

          【讨论】:

            【解决方案5】:

            您需要确保使用 os.path.walk 检查here.

            你只需要提供你想要搜索的目录,然后你就可以在循环的内部调用你的函数,因为你会得到你需要的文件名。

            例如here.

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-04-06
              • 1970-01-01
              • 1970-01-01
              • 2020-08-23
              • 1970-01-01
              • 2019-09-03
              相关资源
              最近更新 更多