SMR
SMR

Reputation: 521

Delete all pdf files in a folder using python

I am trying to convert all pdf files to .jpg files and then remove them from the directory. I am able to convert all pdf's to jpg's but when I try to delete them, I get the error "The process is being used by another person".

Could you please help me?

Below is the code

Below script wil convert all pdfs to jpegs and storesin the same location.

for fn in files:
    doc = fitz.open(pdffile)
    page = doc.loadPage(0)  # number of page
    pix = page.getPixmap()
    fn1 = fn.replace('.pdf', '.jpg')
    output = fn1
    pix.writePNG(output)
    os.remove(fn) # one file at a time.

path = 'D:/python_ml/Machine Learning/New folder/Invoice/'

i = 0
for file in os.listdir(path):
    path_to_zip_file = os.path.join(path, folder)

    if file.endswith('.pdf'):
        os.remove(file)
    i += 1

Upvotes: 0

Views: 408

Answers (1)

zuo
zuo

Reputation: 176

As @K J noted in their comment, most probably the problem is with files not being closed, and indeed your code misses closing the doc object(s).

(Based on the line fitz.open(pdffile), I guess you use the pymupdf library.)

The problematic fragment:

    doc = fitz.open(pdffile)
    page = doc.loadPage(0)  # number of page
    pix = page.getPixmap()
    fn1 = fn.replace('.pdf', '.jpg')
    output = fn1
    pix.writePNG(output)

...should be adjusted, e.g., in the following way:

    with fitz.open(pdffile) as doc:
        page = doc.loadPage(0)  # number of page
        pix = page.getPixmap()
        output = fn.replace('.pdf', '.jpg')
        pix.writePNG(output)

(Side note: the fn1 variable seems to be completely redundant so I got rid of it. Also, shouldn't pdffile be replaced with fn? What pdffile actually is?)

Upvotes: 0

Related Questions