【问题标题】:What is the alternative to Python os.listdir()?Python os.listdir() 的替代方法是什么?
【发布时间】:2018-11-08 17:17:19
【问题描述】:
当我在 python 中执行以下命令时,控制台报错
注意:我正在使用 windows 10 环境
>>> os.listdir()
Traceback (most recent call last):
File "<stdin>, line 1, in <module>
TypeError: listdir() takes exactly 1 argument (0 given)
【问题讨论】:
标签:
python
python-3.x
python-2.7
【解决方案1】:
您需要将 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)
【解决方案2】:
我想你想用
os.listdir(os.getcwd())
这列出了当前工作目录(os.getcwd() 返回路径)
【解决方案3】:
这个 TypeError: listdir() 只需要 1 个参数(给定 0)
当您在 Jupyter Notebook 中运行相同的命令时,通常不会发生,因为路径变量在您启动笔记本时已经设置好了。但是您正在运行 .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)
【解决方案4】:
而不是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])
这应该会为您提供要探索的路径下的文件路径的完整列表。