2012-11-08 110 views
2

我是一个总的Python福利局Python的 - 需要遍历目录寻找TXT文件

我需要遍历一个寻找.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

回答

3

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') 
+0

所以我尝试了这一点,并且我在调用该变量的方式上仍然收到无效的语法错误。 – greyoxide

+0

您还需要在os.listdir(scrptPth):'中的'for file结尾处使用冒号。没有冒号,你会得到一个SyntaxError。 – unutbu

10
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)