![](/img/trans.png)
[英]Merging PDF files using Python and PyPDF2 throws a TypeError
[英]Merging PDF files using Python PyPDF2 and naming new file
我想合並幾個 pdf 並將其中一個 pdf 的名稱用於新文件。
import os
from PyPDF2 import PdfFileMerger
import datetime
pdfs = os.listdir(r'C:\Desktop\Work')
today = datetime.date.today()
# os.listdir will create the list of all files in a directory
merger = PdfFileMerger(strict=False)
# merger is used for merging multiple files into one and merger.append(absfile) will append
the files one by one until all pdfs are appended in the result file.
for file in pdfs:
if file.endswith(".pdf"):
path_with_file = os.path.join(r'C:\Desktop\Work', file)
print(path_with_file)
merger.append(path_with_file, import_bookmarks=False )
merger.write(path_with_file)
merger.close()
但我有一個
error invalid literal for int() with base 10: b'' for merger.write line
我怎樣才能使這個新文件與合並的舊文件具有相同的名稱?
不確定是否是您復制代碼的錯誤,但第二行也應注釋:
# merger is used for merging multiple files into one and merger.append(absfile) will append
the files one by one until all pdfs are appended in the result file.
至於你收到的錯誤,我相信你必須先打開文件,確保它也有被讀取的權限。
要獲得由您合並的每個文件組成的最終文件名,您可以嘗試連接一個字符串。
我試過了,它奏效了,如果它解決了問題,請告訴我:
import os
from PyPDF2 import PdfMerger
import datetime
pdfs = os.listdir(r'C:\Desktop\Work')
today = datetime.date.today()
# os.listdir will create the list of all files in a directory
merger = PdfMerger(strict=False)
# merger is used for merging multiple files into one and merger.append(absfile) will append
# the files one by one until all pdfs are appended in the result file.
final_filename = ''
for file in pdfs:
# Open files
if file.endswith(".pdf"):
final_filename += file.split('.')[-2]
path_with_file = os.path.join(r'C:\Desktop\Work', file)
input = open(path_with_file, 'rb')
print(path_with_file)
print(input.seek(0, os.SEEK_END))
merger.append(input, import_bookmarks=False)
print(final_filename)
merger.write(f'{final_filename}.pdf')
merger.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.