Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I list the contents of a directory in Python?

Tags:

python

path

People also ask

How do I view a directory in Python?

To find out which directory in python you are currently in, use the getcwd() method. Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python. To get it as a bytes object, we use the method getcwdb().

How do I copy the contents of a directory in Python?

The copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil. copy() method also preserving the file's metadata.

How do I get all the text files in a directory in Python?

Use the os. listdir('path') function to get the list of all files of a directory. This function returns the names of the files and directories present in the directory.


import os
os.listdir("path") # returns list

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

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)

glob.glob or os.listdir will do it.