Created
June 13, 2023 16:03
-
-
Save thomasnield/1b4b295b408fd178d712e5b8019a9f88 to your computer and use it in GitHub Desktop.
Python - Iterate and Rename Files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# import required module | |
import os | |
from pathlib import Path | |
import re | |
# assign directory | |
directory = Path('/Users') / 'thomasnield' / 'git' / 'oreilly_essential_math_for_data_science_book' | |
def two_digit_correct(filename: str): | |
return re.sub(r"(?<=[0-9])_(?=[0-9][A-z])", "_0", filename) | |
# iterate over files in | |
# that directory | |
for chapter_folder in os.scandir(directory): | |
if chapter_folder.is_dir(): | |
print(chapter_folder.path) | |
for file in os.scandir(chapter_folder): | |
if file.name.endswith(".py"): | |
os.rename(os.path.join(chapter_folder.path, file.name), os.path.join(chapter_folder.path, two_digit_correct(file.name))) | |
# os.rename(file, two_digit_correct(file.name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment