Skip to content

Instantly share code, notes, and snippets.

@bmwant
Last active July 6, 2017 21:09
Show Gist options
  • Save bmwant/c2fa207720e24bda0809cffb6ff5d353 to your computer and use it in GitHub Desktop.
Save bmwant/c2fa207720e24bda0809cffb6ff5d353 to your computer and use it in GitHub Desktop.
Usage of common methods of os.path module
import os
import glob
# Get current directory
dir_path = os.path.dirname(os.path.realpath(__file__))
# Walk match files by a pattern within directory
glob.glob('your-directory/*')
# Recursively walk through all the files/directories within a folder
def list_directory_files(directory, ext='', full_path=True):
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith(ext):
file_path = os.path.join(root, filename) if full_path else filename
yield file_path
# Rename file
if filename.startswith('bad_name_'):
os.rename(filename, filename[9:])
# Get path for directory parent to the one the file is within
__CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(__CURRENT_DIR, os.pardir))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment