Python Forum
pyPDF2 PDFMerger close pensding file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: pyPDF2 PDFMerger close pensding file (/thread-37832.html)



pyPDF2 PDFMerger close pensding file - japo85 - Jul-27-2022

Hello to everyone!
I have a problem using pyPDF2: I merge some pdf in a directory and I want to delete it after the job is done, but when I try to do it, I can't because one of them (the single pdf) was open by the pdfmerger and I can't delete it. The error is:

Error:
Error in line 395: [WinError 32] Impossibile accedere al file. Il file รจ utilizzato da un altro processo: 'S:\\QUAREP\\Controlli\\12000609\\00_Report\\Vecchio_Nuovo\\temp\\12000609_220726_IP_Figura_2_su_12000609_220616_IP_Figura_2.pdf' Traceback (most recent call last): File "Vecchio_Nuovo_Da_CAD_Pdf_Merge_Snellito.py", line 396, in <module> File "shutil.py", line 513, in rmtree return _rmtree_unsafe(path, onerror) File "shutil.py", line 397, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "shutil.py", line 395, in _rmtree_unsafe os.unlink(fullname)
The code I used is:

rootDir=temp_path for dirName,subDir, fileList in os.walk(rootDir, topdown=False):	merger = PdfFileMerger()	for fname in fileList:	merger.append(PdfFileReader(open(os.path.join(dirName, fname),'rb')))	print (fname) merger.write(str(path2)+(nome_confronto)+".pdf") folder=temp_path for filename in os.listdir(folder):	file_path = os.path.join(folder, filename)	try:	if os.path.isfile(file_path) or os.path.islink(file_path):	os.unlink(file_path)	elif os.path.isdir(file_path):	shutil.rmtree(file_path)	except Exception as e:	print('Failed to delete %s. Reason: %s' % (file_path, e))
How can I resolve it?


RE: pyPDF2 PDFMerger close pensding file - deanhystad - Jul-27-2022

pdfmerger is not leaving the file open, you are. Here you open a file and never close it.
merger.append(PdfFileReader(open(os.path.join(dirName, fname),'rb')))
I would use a context manager to automatically close the file.
with open(os.path.join(dirName, fname),'rb') as file: merger.append(PdfFileReader(file))



RE: pyPDF2 PDFMerger close pensding file - japo85 - Jul-28-2022

(Jul-27-2022, 03:38 PM)deanhystad Wrote: pdfmerger is not leaving the file open, you are. Here you open a file and never close it.
merger.append(PdfFileReader(open(os.path.join(dirName, fname),'rb')))
I would use a context manager to automatically close the file.
with open(os.path.join(dirName, fname),'rb') as file: merger.append(PdfFileReader(file))

Thank you very much!! It works perfectly!


This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.