描述
方法listdir()返回一個包含路徑給定目錄中條目名稱的列表。該列表的順序是任意的。它不包括特殊條目 '.' 和 '..',即使它們存在於目錄中。
path 可以是 str 類型或 bytes 類型。如果路徑是字節類型,則返回的文件名也將是字節類型;在所有其他情況下,它們將是 str 類型。
用法
以下是語法listdir()方法≫
os.listdir(path)
參數
path─ 這是目錄,需要探索。
返回值
此方法返回一個列表,其中包含路徑給定的目錄中條目的名稱。
示例
下麵的例子展示了 listdir() 方法的用法。
#!/usr/bin/python3
import os, sys
# Open a file
path = "d:\\tmp\\"
dirs = os.listdir( path )
# This would print all the files and directories
for file in dirs:
print (file)
結果
當我們運行上麵的程序時,它會產生以下結果——
Applicationdocs.docx test.java book.zip foo.txt Java Multiple Inheritance.htm Java Multiple Inheritance_files java.ppt ParallelPortViewer
相關用法
- Python 3 os.link()用法及代碼示例
- Python 3 os.lchown()用法及代碼示例
- Python 3 os.lstat()用法及代碼示例
- Python 3 os.lseek()用法及代碼示例
- Python 3 os.lchmod()用法及代碼示例
- Python 3 os.lchflags()用法及代碼示例
- Python 3 os.fstatvfs()用法及代碼示例
- Python 3 os.minor()用法及代碼示例
- Python 3 os.close()用法及代碼示例
- Python 3 os.unlink()用法及代碼示例
- Python 3 os.major()用法及代碼示例
- Python 3 os.rmdir()用法及代碼示例
- Python 3 os.fdopen()用法及代碼示例
- Python 3 os.fdatasync()用法及代碼示例
- Python 3 os.isatty()用法及代碼示例
- Python 3 os.rename()用法及代碼示例
- Python 3 os.walk()用法及代碼示例
- Python 3 os.renames()用法及代碼示例
- Python 3 os.makedirs()用法及代碼示例
- Python 3 os.utime()用法及代碼示例
注:本文由純淨天空篩選整理自 Python 3 - os.listdir() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。