简体   繁体   English

Python os.listdir() 的替代方法是什么?

[英]What is the alternative to Python os.listdir()?

When I execute the below command in python, the console gives an error Note: I am working windows 10 environment当我在 python 中执行以下命令时,控制台给出错误注意:我正在Windows 10 环境中工作

>>> os.listdir()

Traceback (most recent call last):

  File "<stdin>, line 1, in <module>

TypeError: listdir() takes exactly 1 argument (0 given)

You need to use listdir() with a path like:您需要将 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)

I think you want to use我想你想用

os.listdir(os.getcwd())

This lists the current working directory ( os.getcwd() returns the path)这列出了当前工作目录( os.getcwd()返回路径)

This TypeError: listdir() takes exactly 1 argument (0 given) generally doesn't occur when you run the same command in Jupyter Notebook as path variables are already settled up when you launch a notebook.当您在 Jupyter Notebook 中运行相同的命令时,通常不会发生此TypeError: listdir() 需要 1 个参数(给定 0) ,因为在您启动笔记本时路径变量已经确定。 But you are running .py scripts you can sort it below way.但是您正在运行 .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

Or you can manually give path as,或者您可以手动将路径指定为,

import os
path='/home/directory1/sub_directory'
a=os.listdir(path)

You can print a to checkout您可以打印一个结帐

print(a)

Instead of os.listdir() , os.walk() is a way better alternative -而不是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])

This should give you a complete list of the file paths under the path you want to explore.这应该为您提供要探索的路径下的文件路径的完整列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM