os.rename() 由于不需要的“/”而中断,不会被替换

os.rename() disrupted due to unwanted "/", which won't get replaced

我正在尝试使用通过 PdfFileReaderPyPDF2 库中获得的信息重命名文件。有时,信息(在这种情况下,使用 reader.metadata.title 获得的标题包含反斜杠 ("/"),这会破坏重命名过程,因为它们被视为我在 os.rename() 中指示为目标路径的路径中的目录级别. 我试图通过在获得的字符串上应用 os.replace() 方法来用“-”替换反斜杠,但由于某种原因,当我尝试重命名时,这不起作用导致 FileNotFoundError。我已经仔细检查并且包含 reader.metadata.title 的变量的类型是 str,所以理论上 os.replace() 方法应该成功应用。下面我的输出示例中显示的是“TOC/TOC”某种需要以不同方式处理的编码?谢谢。

我的代码:

from PyPDF2 import PdfReader


for pdf_file in os.listdir(downloads_path):
    if pdf_file.endswith(".pdf"):
        current_file_path = os.path.join(downloads_path, pdf_file)
        reader = PdfReader(open(current_file_path, "rb"))
        new_name_pdf_file = reader.metadata.title
        new_name_pdf_file.replace("/", "-")

        # output example: 'Outside Back Cover - Graphical abstract TOC/TOC in double column/Cover image legend if applicable, Bar code, Abstracting and Indexing information'
        print(new_name_pdf_file)
        new_pdf_destination = os.path.join(destination_path, new_name_pdf_file)
        os.rename(current_file_path, new_pdf_destination)

输出错误示例:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/me/Documents/temporary_downloads_folder/Outside-Back-Cover---Graphical-abstract-TOC-TOC-in-double-column-C_2022_Nano.pdf' -> '/Users/me/Documents/destination_folder/Outside Back Cover - Graphical abstract TOC/TOC in double column/Cover image legend if applicable, Bar code, Abstracting and Indexing information.pdf'

new_name_pdf_file.replace("/", "-")

并不像您认为的那样。它不会更改 new_name_pdf_file 指向的字符串。事实上:它不能那样做。 python 中的字符串是不可变的。它们无法更改。相反,它会创建一个完成替换的新字符串。

将行更改为

new_name_pdf_file = new_name_pdf_file.replace("/", "-")

它应该可以工作。