![]() |
| 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: 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. Thank you very much!! It works perfectly! |