2010-05-03 34 views

回答

156
import os 
os.listdir("path") # returns list 
14

glob.globos.listdir會這樣做。

+0

'import glob' ENTER'glob.glob(r'c:\ users')'ENTER似乎只返回'['c:\\ users']'。這是爲什麼?我想使用glob.glob,因爲正如其他用戶指出的那樣,它應該會返回目錄的內容,同時也會忽略隱藏的文件。這個很重要。 – Musixauce3000 2016-04-14 19:49:55

9

os module處理所有的東西。

os.listdir(path)

返回包含在由路徑給出的目錄中的條目名稱的列表。 該列表以任意順序排列。它不包括特殊條目''。'和 '..',即使它們存在於目錄中。

可用性:Unix,Windows。

36

One way

import os 
os.listdir("/home/username/www/") 

Another way

glob.glob("/home/username/www/*") 

Examples found here

上面的glob.glob方法不會列出隱藏文件。

import os 
start_path = '.' # current directory 
for path,dirs,files in os.walk(start_path): 
    for filename in files: 
     print os.path.join(path,filename) 
+0

glob.glob在與glob.glob(「/ home/username/www /.*」)一起使用時會列出隱藏文件(我認爲你的意思是Unix文件系統環境中的'.XYZ'文件)? – 2012-08-03 17:48:58

+0

是的,我的意思是以點開頭的文件。您提供的示例將用於匹配隱藏文件(僅隱藏文件)。 – 2012-08-04 19:10:49

+0

我剛剛導入了glob並使用了glob.glob(r'c:\ users'),但它只返回了'['c:\\ users']' – Musixauce3000 2016-04-14 19:43:19

26

os.walk可根據需要遞歸使用。另一個是os.walk

def print_directory_contents(sPath): 
     import os          
     for sChild in os.listdir(sPath):     
      sChildPath = os.path.join(sPath,sChild) 
      if os.path.isdir(sChildPath): 
       print_directory_contents(sChildPath) 
      else: 
       print(sChildPath) 
1

下面的代碼將列出目錄和目錄中的文件:

相關問題