-3

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)
Linny
  • 818
  • 1
  • 9
  • 22
Siluveru Kiran Kumar
  • 699
  • 1
  • 10
  • 16
  • Does this answer your question? [Python: os.listdir alternative/certain extensions](https://stackoverflow.com/questions/3122514/python-os-listdir-alternative-certain-extensions) – Red Jul 08 '20 at 02:41

4 Answers4

7

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)
Pikamander2
  • 7,332
  • 3
  • 48
  • 69
Linny
  • 818
  • 1
  • 9
  • 22
2

I think you want to use

os.listdir(os.getcwd())

This lists the current working directory (os.getcwd() returns the path)

hda
  • 192
  • 1
  • 4
1

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)
0

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.

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51