Wer auch auf einem Berg an kryptisch benannten PDF-Dateien sitzt und diese gerne sinnvoll nach Ihren Titel benannt sehen würde, findet hier eine Möglichkeit, dies mit einfachen Python-Mitteln umzusetzten.

import os
import pdftitle
from glob import glob
import tkinter as tk
from tkinter import filedialog
import re

def sanitize_filename(name):
    # Replace newline characters with nothing
    name = name.replace('\n', '')

    # Remove special characters except ä and ö, then convert to lowercase
    name = re.sub('[^a-zA-Z0-9 äö\.]', '_', name)
    name = name.lower()

    return name


def select_directory():
    root = tk.Tk()
    root.withdraw()  # Hides the root window
    root.wm_attributes('-topmost', 1)  # Brings the window to the front
    directory = filedialog.askdirectory()  # Shows directory selection dialog
    return directory

def rename_pdf_files():
    # Get the directory that contains your PDF files
    pdf_directory = select_directory()

    # Get a list of all PDF files in the directory
    pdf_files = glob(os.path.join(pdf_directory, '*.pdf'))

    # Process each PDF file
    for pdf_file in pdf_files:
        try:
            # Extract the title from the PDF
            title = pdftitle.get_title_from_file(pdf_file)

            # Sanitize the title to ensure it's safe to use as a filename
            safe_title = sanitize_filename(title)

            # Construct the new filename
            new_filename = f"{safe_title}.pdf"

            # Rename the file
            os.rename(pdf_file, os.path.join(pdf_directory, new_filename))
        except Exception as e:
            print(f"Error processing file {pdf_file}: {e}")

if __name__ == "__main__":
    rename_pdf_files()

Um die entsprechende virtuelle Umgebung zu erstellen:

python3 -m venv .venv
source .venv/bin/activate
pyton3 -m pip install pdftitle
Author

Write A Comment

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.