[英]What is the alternative to Python os.listdir()?
當我在 python 中執行以下命令時,控制台給出錯誤注意:我正在Windows 10 環境中工作
>>> os.listdir()
Traceback (most recent call last):
File "<stdin>, line 1, in <module>
TypeError: listdir() takes exactly 1 argument (0 given)
您需要將 listdir() 與如下路徑一起使用:
#!/usr/bin/python
import os
# Open a file
path = "/var/www/html/"
dirs = os.listdir(path)
# This would print all the files and directories
for file in dirs:
print(file)
我想你想用
os.listdir(os.getcwd())
這列出了當前工作目錄( os.getcwd()
返回路徑)
當您在 Jupyter Notebook 中運行相同的命令時,通常不會發生此TypeError: listdir() 需要 1 個參數(給定 0) ,因為在您啟動筆記本時路徑變量已經確定。 但是您正在運行 .py 腳本,您可以按以下方式對其進行排序。
import os #importing library
path=os.getcwd() #will return path of current working directory in string form
a=os.listdir(path) #will give list of items in directory at <path> location same as bash command "ls" on a directory
或者您可以手動將路徑指定為,
import os
path='/home/directory1/sub_directory'
a=os.listdir(path)
您可以打印一個結帳
print(a)
而不是os.listdir()
, os.walk()
是一種更好的選擇 -
path = 'set/to/your/path'
filetups = [(r,f) for r,d,f in os.walk(path)]
print([i+'/'+k for i,j in filetups for k in j])
這應該為您提供要探索的路徑下的文件路徑的完整列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.