【问题标题】:Python - Need to loop through directories looking for TXT filesPython - 需要遍历目录以查找 TXT 文件
【发布时间】:2012-11-08 23:30:25
【问题描述】:

我是个 Python 新手

我需要遍历一个目录来查找 .txt 文件,然后单独读取和处理它们。我想进行设置,以便脚本所在的任何目录都被视为此操作的根目录。例如,如果脚本在 /bsepath/workDir 中,那么它将遍历 workDir 及其子项中的所有文件。

到目前为止我所拥有的是:

#!/usr/bin/env python

import os

scrptPth = os.path.realpath(__file__)

for file in os.listdir(scrptPth)
    with open(file) as f:
        head,sub,auth = [f.readline().strip() for i in range(3)]
        data=f.read()
        #data.encode('utf-8')

pth = os.getcwd()

print head,sub,auth,data,pth

这段代码给了我一个无效的语法错误,我怀疑这是因为os.listdir 不喜欢标准字符串格式的文件路径。另外我不认为我正在做正确的循环动作。如何在循环操作中引用特定文件?是否打包为变量?

任何帮助都是appriciated

【问题讨论】:

    标签: python


    【解决方案1】:
    import os, fnmatch
    
    def findFiles (path, filter):
        for root, dirs, files in os.walk(path):
            for file in fnmatch.filter(files, filter):
                yield os.path.join(root, file)
    

    像这样使用它,它会在给定路径中的某处找到所有文本文件(递归):

    for textFile in findFiles(r'C:\Users\poke\Documents', '*.txt'):
        print(textFile)
    

    【讨论】:

      【解决方案2】:

      os.listdir 需要一个目录作为输入。因此,要获取脚本所在的目录,请使用:

      scrptPth = os.path.dirname(os.path.realpath(__file__))
      

      另外,os.listdir 只返回文件名,而不是完整路径。 所以open(file) 将不起作用,除非当前工作目录恰好是脚本所在的目录。要解决此问题,请使用 os.path.join:

      import os
      
      scrptPth = os.path.dirname(os.path.realpath(__file__))
      
      for file in os.listdir(scrptPth):
          with open(os.path.join(scrptPth, file)) as f:
      

      最后,如果要递归遍历子目录,请使用os.walk

      import os
      
      scrptPth = os.path.dirname(os.path.realpath(__file__))
      
      for root, dirs, files in os.walk(scrptPth):
          for filename in files:
              filename = os.path.join(root, filename)
              with open(filename, 'r') as f:
                  head,sub,auth = [f.readline().strip() for i in range(3)]
                  data=f.read()
                  #data.encode('utf-8')
      

      【讨论】:

      • 所以我试过了,但在调用该变量时仍然遇到无效的语法错误。
      • for file in os.listdir(scrptPth): 的末尾还需要一个冒号。没有冒号,你会得到一个 SyntaxError。
      猜你喜欢
      • 2018-03-17
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多