Python 簡單獲取目錄下的所有檔案

2021-09-30 16:42:27 字數 941 閱讀 7355

1.使用 os.walk()

**:

import os

path = "d:/test"

fns = [os.path.join(root,fn) for root, dirs, files in os.walk(path) for fn in files]

for f in fns:

print f

結果: 路徑或檔名為中文的話會顯示亂碼

c:\python27\python.exe e:/documents/test/aatest.py

d:/test\1.txt

d:/test\��.txt

d:/test\����\1.txt

d:/test\����\��.txt

process finished with exit code 0

2. 使用 scandir.walk()

**:

import scandir

path = "d:/test"

fns = [os.path.join(root, fn) for root, dirs, files in scandir.walk(path) for fn in files]

for f in fns:

print f

結果:出現中文無亂碼現象

c:\python27\python.exe e:/documents/test/aatest.py

d:/test\1.txt

d:/test\二.txt

d:/test\測試\1.txt

d:/test\測試\二.txt

process finished with exit code 0

ps:

os.walk()的詳細解釋可以參考: 

python 獲取當前目錄下的檔案目錄和檔名

os模組下有兩個函式 os.walk os.listdir 1 coding utf 8 23 import os 45 deffile name file dir 6for root,dirs,files in os.walk file dir 7print root 當前目錄路徑 8print ...

python獲取目錄下所有檔案的方法

os.walk 函式宣告www.cppcns.com walk top,topdown true,onerror none 1.引數top表示需要遍歷的目錄樹的路徑 2.引數topdown的預設值是 true 表示首先返回目錄樹下的檔案,然後在遍歷目錄樹的子目錄.topdown的值為 false 時...

python 獲取指定目錄下各目錄占用的空間大小

語言 python3 功能 獲取指定目錄下各目錄占用的空間大小 獲取指定目錄下各目錄占用的空間 coding utf 8 import os,time,platform,sys from threading import thread path,file 1 sys0 platform.system...