如何在 python 中自动命名 pdf 文件
How to automatically name a pdf file in python
我写了一个代码,将 pdf 合并到一个特定的文件夹中。现在我想做的是为我合并的 pdf 创建自动文件名。假设列表中的第一个 pdf 名为:'Aaa 1.pdf'。我希望 python 自动将文件保存为 'Aaa.pdf'。所以每次我使用 python 合并一些东西时,它应该删除文件名的最后一个单词,然后在没有它的情况下保存名称。
这是我的代码:
import PyPDF2
from PyPDF2 import PdfFileMerger
import os
path = "/PATH/"
pdf_files = [f for f in os.listdir(path) if f.endswith('.pdf')]
merger = PdfFileMerger()
for files in pdf_files:
merger.append(path+files)
if not os.path.exists(path+"merged.pdf"):
merger.write(path+"merged.pdf")
merger.close()
有什么办法吗?
另外,如果我希望列表中的第三个或第四个文件也这样做怎么办?
如果名称是 'Aaa 1.pdf',您可以像这样创建字符串 'Aaa.pdf':
#original_name = 'Aaa 1.pdf'
original_name = pdf_files[0]
original_name_split = original_name.split(' ')
new_name = ''.join(original_name_split[:-1]) + '.pdf'
然后您可以使用它来保存您的文件:
if not os.path.exists(path + new_name):
merger.write(path + new_name)
我写了一个代码,将 pdf 合并到一个特定的文件夹中。现在我想做的是为我合并的 pdf 创建自动文件名。假设列表中的第一个 pdf 名为:'Aaa 1.pdf'。我希望 python 自动将文件保存为 'Aaa.pdf'。所以每次我使用 python 合并一些东西时,它应该删除文件名的最后一个单词,然后在没有它的情况下保存名称。 这是我的代码:
import PyPDF2
from PyPDF2 import PdfFileMerger
import os
path = "/PATH/"
pdf_files = [f for f in os.listdir(path) if f.endswith('.pdf')]
merger = PdfFileMerger()
for files in pdf_files:
merger.append(path+files)
if not os.path.exists(path+"merged.pdf"):
merger.write(path+"merged.pdf")
merger.close()
有什么办法吗? 另外,如果我希望列表中的第三个或第四个文件也这样做怎么办?
如果名称是 'Aaa 1.pdf',您可以像这样创建字符串 'Aaa.pdf':
#original_name = 'Aaa 1.pdf'
original_name = pdf_files[0]
original_name_split = original_name.split(' ')
new_name = ''.join(original_name_split[:-1]) + '.pdf'
然后您可以使用它来保存您的文件:
if not os.path.exists(path + new_name):
merger.write(path + new_name)