Listing directories in Python

/ Published in: Python
Save to your folder(s)

Copy this code and paste it in your HTML
  1. #
  3. # Use a one-line list comprehension to get all the files in a given directory with a given extension.
  4. import os
  5. dir = '.'
  6. ext = '.txt'
  7. txt_files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) and f.endswith(ext)]
  9. # os.path.join joins a directory and a filename into a path. You can also split a path name into directory and file with
  10. # os.path.split(), and you can split a filename with extension into filename and extension with os.path.splitext()
  11. # os.path.expandUser() will expand '~' to the absolute path of the current user's home directory on Windows, Linux or Mac
  13. # The rest of the os.path module:
  14. #

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.