Skip to content

Instantly share code, notes, and snippets.

@seanh
Created November 12, 2009 11:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanh/232828 to your computer and use it in GitHub Desktop.
Save seanh/232828 to your computer and use it in GitHub Desktop.
List all the files in a directory with a one-line list comprehension (Python)
# http://www.diveintopython.org/file_handling/os_module.html
# Use a one-line list comprehension to get all the files in a given directory with a given extension.
import os
dir = '.'
ext = '.txt'
txt_files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) and f.endswith(ext)]
# os.path.join joins a directory and a filename into a path. You can also split a path name into directory and file with
# os.path.split(), and you can split a filename with extension into filename and extension with os.path.splitext()
# os.path.expandUser() will expand '~' to the absolute path of the current user's home directory on Windows, Linux or Mac
# The rest of the os.path module:
# http://docs.python.org/lib/module-os.path.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment