Python datando arquivos .md

Renomeando arquivos markdown no formato de posts para blogs estáticos Jekyll.

import datetime
import logging
import os
import pathlib
import re

logging.basicConfig(level=logging.INFO)

ignore_dirs = ["venv", ".ipynb"]
target_file_extensions = (".md", ".ipynb")
ignore_files = "README"


def date_file(base_dir):
    counter = 0
    for root, dirs, files in os.walk(base_dir):
        for name in files:
            if any(elem in root for elem in ignore_dirs):
                continue
            # Check if already starts with date
            match = re.match(r"\d{4}-\d{2}-\d{2}.*", name)
            if (
                name.endswith(target_file_extensions)
                and not name.startswith(ignore_files)
                and not match
            ):
                file_path = os.path.join(root, name)
                file = pathlib.Path(file_path)
                file_creation_date = (
                    datetime.datetime.fromtimestamp(file.stat().st_ctime)
                    .date()
                    .strftime("%Y-%m-%d")
                )
                logging.info("File path: %s" % file_path)
                logging.info("File creation date: %s" % file_creation_date)
                new_file_path = os.path.join(
                    root, file_creation_date + "-" + name
                )
                # Avoid overwrite files
                if os.path.isfile(new_file_path):
                    logging.warning("File %s already exists" % file_path)
                    continue
                os.rename(file_path, new_file_path)
                logging.info("New file path: %s" % new_file_path)
                counter += 1
    logging.info("Files renamed %s" % counter)


if __name__ == "__main__":
    date_file(".")

Updated: