python os.walk()和os.listdir()

阿蘇爾發表於2018-04-12

本部分內容的組織關係:python3.6.5文件

\to
python標準庫
\to
16 通用作業系統服務
\to
16.1.5 檔案和目錄
對於官方文件的學習可以和每週一個python模組相互協作著進行。
還可以檢視如何系統的學習python標準庫

os.listdir(path = ‘.’)

入口為path給定的目錄,函式返回一個列表,列表順序是隨機的,並且不包括入口’.’,’..’,即使它們在目錄中存在。

os.listdir(path=’.’)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries ‘.’ and ‘..’ even if they are present in the directory.

os.walk(top, topdown=True, onerror=None, followlinks=False)

遍歷頂級目錄下的每個目錄,每個目錄返回一個三元組(路徑,目錄名,檔名)。預設是自上而下遍歷,將topdown改為False則自下而上遍歷。目錄名是路徑下的子目錄名列表,排除掉’.’,’..’。注意,這些名字不包含路徑。如果想得到全路徑,可以使用os.join(dirpath, name)。

os.walk(top, topdown=True, onerror=None, followlinks=False)
Generate the file names in a directory tree by walking the tree either top-down or bottom-up.
dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).
“`

相關文章