os.listdir()
可以獲得一個(gè)目錄中所有文件或者子目錄槐臀。
如果你只想要文件的話,你也可以用os.path.isfile()
把其他的過(guò)濾掉:
from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
或者你可以用os.walk()
,它遍歷每個(gè)目錄將會(huì)返回兩個(gè)列表(一個(gè)文件列表,一個(gè)目錄列表),如果你想要頂層目錄只需要在第一次迭代后break一下即可.
from os import walk
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break
應(yīng)用
如果是打包下載某一個(gè)目錄下面所有文件,包括文件夾呢皿渗?打包文件解壓后包含原始的文件目錄層級(jí)關(guān)系。
import zipfile
zipFileFullPathName='/storage/asset/zips/10000/10000.zip'
filePath='/storage/asset/files/10000/'
relatePath='/storage/asset/files'
with zipfile.ZipFile(zipFileFullPathName, 'w', zipfile.ZIP_DEFLATED) as myzip:
for folder, subfolders, fileNames in os.walk(filePath):
for fileName in fileNames:
fileFullPathName=os.path.join(folder,fileName)
#relatePath 相對(duì)路徑用于壓縮包解壓后的根目錄開始的目錄蒂窒。
#例如壓縮 /storage/asset/files/10000目錄下所有文件帖努,
#relatePath設(shè)置為 /storage/asset/files后最終壓縮包解壓的根目錄是10000文件夾開始
myzip.write(fileFullPathName,os.path.relpath(fileFullPathName,relatePath))