1

I'm currently having some issues removing a file in python. I am creating a temporary file for pdf to image conversion. It is housed in a folder that holds a .ppm file and converts it to a .jpg file. It then deletes the temporary .ppm file. Here is the code:

    import pdf2image
    from PIL import Image
    import os

    images = pdf2image.convert_from_path('Path to pdf.pdf', output_folder='./folder name')
    file = ''
    for files in os.listdir('./folder name'):
        if files.endswith(".ppm"):
            file = files        
    path = os.path.join('folder name',file)
    im = Image.open(path)
    im.save("Path to image.jpg")
    im.close()
    os.remove(path)

The issue is at the end in the os.remove(path). I get the following error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'path to ppm file'

I would appreciate any help and thanks in advance.

1 Answers1

-1

Not really the answer to your question, but you can just output in the correct format at the start, and avoid the issue in the first place:

pdf2image.convert_from_path('Path to pdf.pdf', output_folder='./folder name', fmt='jpg')

To actually answer your question, I'm not sure why you're having the issue, because really the close() should prevent this problem. Perhaps check out this answer and try using a with statement? Or maybe the permissions release is just delayed, I'm curious what throwing that remove in a loop for as long as it throws an exception would do.

Edit: To set the name, you'll want to do something like:

images = pdf2image.convert_from_path('Path to pdf.pdf', output_folder='./folder name', fmt='jpg')
for image in images:
    # Save the image

The pdf2image documentation looks like it recommends using a temporary folder, like in this example, and then you can just .save(...) the PIL image:

import tempfile

with tempfile.TemporaryDirectory() as path:
     images_from_path = convert_from_path('/home/kankroc/example.pdf', output_folder=path)
     # Do something here

Edit: I realized that the reason it was in use is probably because you need to close() all the images in images. You should read up on the pdf2image documentation and about the PIL images that it spits out for more details.

Daniel Centore
  • 3,220
  • 1
  • 18
  • 39