Encounters
os.listdir() ⚬|encounter|ENC|20260715120928-00-•
Updated todo list
Yes, Python has several equivalents to the Unix
lscommand in theosmodule:
os.listdir(path='.')
- Returns a list of filenames/directory names in the specified directory
- Most direct equivalent to
lsimport os files = os.listdir('/path/to/directory') # Returns ['file1.txt', 'file2.py', ...]
os.scandir(path='.')(Python 3.5+)
- Returns an iterator of
os.DirEntryobjects- More efficient than
listdir()when you need file attributes (size, type, etc.)import os with os.scandir('/path/to/directory') as entries: for entry in entries: print(entry.name, entry.is_file(), entry.is_dir())
os.walk(path)
- For recursive directory traversal (like
ls -R)import os for dirpath, dirnames, filenames in os.walk('/path/to/directory'): print(f"Directory: {dirpath}") print(f"Files: {filenames}")The
shutilmodule doesn’t have a directlsequivalent - it focuses on file operations like copying and moving.Note: The newer
Link to originalpathlibmodule (not inosorshutil) also providesPath.iterdir()which is a more modern, object-oriented approach.
@Claude ○˒
(echo:: @ ᯤ ᯤ ᯤ)