list all the files in the current directory and all subdirectories in python

You can use the os module to recursively traverse through all the directories and subdirectories in the current directory and list all the files using the os.listdir() method. Here's a sample code to achieve this:

main.py
import os

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        for file in files:
            print(os.path.join(root, file))

list_files(".")
175 chars
9 lines

In the above code:

  • The os.walk method is used to recursively traverse through all the directories and subdirectories in the current directory.
  • The current directory is represented by "." (dot).
  • Inside the os.walk() method, the for loop is used to iterate through all the files in each directory and subdirectory.
  • The os.path.join method is used to get the full path of each file.
  • The print statement is used to print the full path of each file.

You can modify this code to suit your needs, such as storing the file paths in a list or writing them to a file.

gistlibby LogSnag