250

Can’t be hard, but I’m having a mental block.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270

8 Answers8

344
import os
os.listdir("path") # returns list
user85461
  • 6,510
  • 2
  • 34
  • 40
75

One way:

import os
os.listdir("/home/username/www/")

Another way:

glob.glob("/home/username/www/*")

Examples found here.

The glob.glob method above will not list hidden files.

Since I originally answered this question years ago, pathlib has been added to Python. My preferred way to list a directory now usually involves the iterdir method on Path objects:

from pathlib import Path
print(*Path("/home/username/www/").iterdir(), sep="\n")
Trey Hunner
  • 10,975
  • 4
  • 55
  • 114
  • Would glob.glob list hidden files (I assume you mean `.XYZ` files in a Unix file-system context), when used with `glob.glob("/home/username/www/.*")` ? – Andy Finkenstadt Aug 03 '12 at 17:48
  • Yes I mean files beginning with a dot. The example you gave would work for matching hidden files (and only hidden files). – Trey Hunner Aug 04 '12 at 19:10
  • I just imported glob and used glob.glob(r'c:\users') but it only returned `['c:\\users']` – Musixauce3000 Apr 14 '16 at 19:43
  • 1
    @Musixauce3000: You'll want to do `glob.glob(r'c:\users\*')` (glob it doesn't actually list directories, but expands asterisks and such which accomplishes a similar task). – Trey Hunner Apr 15 '16 at 07:04
48

os.walk can be used if you need recursion:

import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
19

glob.glob or os.listdir will do it.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
Tuomas Pelkonen
  • 7,783
  • 2
  • 31
  • 32
  • 1
    `import glob` ENTER `glob.glob(r'c:\users')` ENTER only seems to return `['c:\\users']`. Why is that? I'd like to use glob.glob because as other users have pointed out, it supposedly returns the contents of a directory while also ignoring hidden files. This is important. – Musixauce3000 Apr 14 '16 at 19:49
  • because you have to specify a wildcard with `glob`: `glob.glob(r'c:\users\*')` – Jean-François Fabre Nov 18 '18 at 15:35
15

The os module handles all that stuff.

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Availability: Unix, Windows.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
zdav
  • 2,752
  • 17
  • 15
7

In Python 3.4+, you can use the new pathlib package:

from pathlib import Path
for path in Path('.').iterdir():
    print(path)

Path.iterdir() returns an iterator, which can be easily turned into a list:

contents = list(Path('.').iterdir())
jpyams
  • 4,030
  • 9
  • 41
  • 66
5

Since Python 3.5, you can use os.scandir.

The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file to know if it's a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:

example to list a directory and print files bigger than max_value bytes:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

(read an extensive performance-based answer of mine here)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

Below code will list directories and the files within the dir. The other one is os.walk

def print_directory_contents(sPath):
        import os                                       
        for sChild in os.listdir(sPath):                
            sChildPath = os.path.join(sPath,sChild)
            if os.path.isdir(sChildPath):
                print_directory_contents(sChildPath)
            else:
                print(sChildPath)
Heenashree Khandelwal
  • 659
  • 1
  • 13
  • 30