【问题标题】:How to Rename Multiple pdf files to their titles using python [duplicate]如何使用python将多个pdf文件重命名为其标题[重复]
【发布时间】:2021-12-05 16:25:44
【问题描述】:

我是一名新手编码员。我需要实现上述目标,因为我正在使用大约 600 个随机名称下载的 pdf,并希望将它们更改为各自的标题。自过去几天以来,我一直在尝试解决此问题,但无处可去。我确实找到了一个不错的 4 年旧代码,它完全符合我的要求。但它似乎存在一些问题并且不适用于 Python 3.10。

这是我找到的代码:https://github.com/jdmonaco/pdf-title-rename

【问题讨论】:

    标签: python


    【解决方案1】:

    有很多不同的方法可以回答这个问题,但在我看来,最简单的方法是使用 Python 的模块 os

    要重命名许多文件,您需要做的第一件事是将所有 PDF 文件放在一个文件夹中。完成后,您可以使用以下代码:

    def batchRenmePDF(folder, newName):
        import os
    
        suffix = 0
    
        for each_pdf in os.listdir(folder):
            suffix += 1
    
            path = os.path.join(folder,each_pdf)
    
            os.rename(path,f"{newName}_{suffix}.png")
    

    这是上面代码的更深入版本:

    def batchRenmePDF(folder, newName):
        '''
        A function to quickly rename PDFs
    
        args:
            folder (str, path): The path for the folder with all the PDFs
            newName (str): The name for the new PDFs (Do not include filetypes)
        '''
        # Import required modules
        import os
    
        # Make sure the user's folder exists
        if os.path.exists(folder):
            pass
        else:
            print("Folder does not exist")
            exit()
    
        # If the user added the filetype in the newName, replace it with nothing
        if str(newName).endswith(".pdf") or str(newName).endswith(".PDF"):
            newName = str(newName).replace(".pdf","")
            newName = str(newName).replace(".PDF","")
        else:
            pass
    
        # Create the variable for the suffix for all the PDFs
        suffix = 0
    
        # Loop through all PDFs in the folder the user gave
        for each_pdf in os.listdir(folder):
            # Add 1 to the suffix so each time the PDF will have a different number
            suffix += 1
    
            # Create the path for the PDF using the folder path and the PDF name
            path = os.path.join(folder,each_pdf)
    
            # Actually renaming the PDFs
            os.rename(path,f"{newName}_{suffix}.png")
    

    【讨论】:

    • 如果你很好奇:我想大部分的反对意见是因为这个问题在不必要的措辞上很重要,但细节很少(例如,当他们尝试代码时甚至会发生什么实际错误 - 什么是“一些问题”吗?)。
    猜你喜欢
    • 2015-08-22
    • 2016-07-03
    • 2021-02-20
    • 1970-01-01
    • 2011-03-25
    • 2019-09-02
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多