简体   繁体   中英

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

>>> 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:

#!/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)

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. But you are running .py scripts you can sort it below way.

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 -

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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