Write a Python script that lists all files under a given directory path.
💡 Model Answer
You can use the built‑in os module to walk through a directory tree. The following script accepts a path argument and prints every file it finds:
import os
import sys
def list_files(root):
for dirpath, dirnames, filenames in os.walk(root):
for f in filenames:
print(os.path.join(dirpath, f))
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python list_files.py <directory>")
sys.exit(1)
list_files(sys.argv[1])os.walk yields a 3‑tuple for each directory: the path, a list of subdirectories, and a list of files. The script concatenates the directory path with each filename to produce an absolute path. Complexity is O(n) where n is the total number of files and directories visited. The script handles nested directories and ignores symbolic links by default. For large trees, you might want to add error handling for permission issues or use pathlib for a more modern approach.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500