To print a list of files in a directory and its subdirectories in Python, you can use the “os.walk()” function. The os.walk() function generates file names in a directory tree by walking the tree either top-down or bottom-up.
Here’s a step-by-step guide on how to print a list of files in a directory and its subdirectories in Python:
- Import the os module.
- Define the starting directory.
- Use the os.walk() function to iterate through the directory tree.
- For each directory in the tree, print the file names.
Here’s an example.
import os
# Step 2: Define the starting directory
start_directory = "/Users/krunallathiya/Desktop/"
# Step 3: Use the os.walk() function to iterate through the directory tree
for root, dirs, files in os.walk(start_directory):
# Step 4: Print the file names
for file_name in files:
# Combine the root directory path with the file name
full_path = os.path.join(root, file_name)
print(full_path)
Output
/Users/krunallathiya/Desktop/Code/R/node_modules/fetch-blob/index.js
/Users/krunallathiya/Desktop/Code/R/node_modules/fetch-blob/README.md
/Users/krunallathiya/Desktop/Code/R/node_modules/fetch-blob/package.json
/Users/krunallathiya/Desktop/Code/R/node_modules/fetch-blob/from.js
/Users/krunallathiya/Desktop/Code/R/node_modules/fetch-blob/file.js
/Users/krunallathiya/Desktop/Code/R/node_modules/fetch-blob/index.d.ts
/Users/krunallathiya/Desktop/Code/R/node_modules/fetch-blob/streams.cjs
/Users/krunallathiya/Desktop/Code/R/gol/hello.go
This script will print the full path of all files in the specified directory and its subdirectories.
That’s it.