2011-02-07 186 views

回答

6

你可以嘗試這樣的:

import os.path 
def print_it(x, dir_name, files): 
    print dir_name 
    print files 

os.path.walk(your_dir, print_it, 0) 

注:os.path.walk的第三個參數是你想要的。你會得到它作爲回調的第一個ARG

+0

這雖然會因工作os`如何處理``path`,你應該* *總進口`os.path`明確。 – 2011-02-07 06:14:09

+0

固定!感謝您的評論。 – luc 2011-02-07 06:35:50

2

你可以嘗試glob

import glob 

for file in glob.glob('log-*-*.txt'): 
    # Etc. 

glob不遞歸工作(據我所知),所以如果你的日誌文件夾中在那個目錄裏面,你最好在看什麼Ignacio Vazquez-Abrams發佈。

3
import os 
# location of directory you want to scan 
loc = '/home/sahil/Documents' 
# global dictonary element used to store all results 
global k1 
k1 = {} 

# scan function recursively scans through all the diretories in loc and return a dictonary 
def scan(element,loc): 

    le = len(element) 

    for i in range(le): 
     try: 

      second_list = os.listdir(loc+'/'+element[i]) 
      temp = loc+'/'+element[i] 
      print "....." 
      print "Directory %s " %(temp) 
      print " " 
      print second_list 
      k1[temp] = second_list 
      scan(second_list,temp) 

     except OSError: 
      pass 

    return k1 # return the dictonary element  


# initial steps 
try: 
    initial_list = os.listdir(loc) 
    print initial_list 
except OSError: 
    print "error" 


k =scan(initial_list,loc) 
print " ..................................................................................." 
print k 

我將此代碼作爲目錄掃描器爲我的音頻播放器製作播放列表功能,它將遞歸掃描目錄中存在的所有子目錄。

1

如果您需要檢查多個文件類型,使用

glob.glob("*.jpg") + glob.glob("*.png") 

水珠不關心在列表中文件的順序。如果您需要按文件名排序的文件,使用

sorted(glob.glob("*.jpg")) 
2

您可以從目錄遞歸這樣的列表裏的文件。

from os import listdir 
from os.path import isfile, join, isdir 

def getAllFilesRecursive(root): 
    files = [ join(root,f) for f in listdir(root) if isfile(join(root,f))] 
    dirs = [ d for d in listdir(root) if isdir(join(root,d))] 
    for d in dirs: 
     files_in_d = getAllFilesRecursive(join(root,d)) 
     if files_in_d: 
      for f in files_in_d: 
       files.append(join(root,f)) 
    return files 
2
import os 
rootDir = '.' 
for dirName, subdirList, fileList in os.walk(rootDir): 
    print('Found directory: %s' % dirName) 
    for fname in fileList: 
     print('\t%s' % fname) 
    # Remove the first entry in the list of sub-directories 
    # if there are any sub-directories present 
    if len(subdirList) > 0: 
     del subdirList[0]