mohamez
mohamez

Reputation: 109

I'm getting the "FileNotFoundError:" in Python, even though some files are successfully found on the same directory

I want to rename PDF files on this directory:

directory

Based on a list I created in this code:

import pdfplumber
import os


pdf_name = []

for filename in os.listdir("."):
    if filename.endswith(".pdf"):
        with pdfplumber.open(filename) as pdf:
            page = pdf.pages[0]
            text = page.extract_text()

            li = text.split(' ')
            for item in li:
                if item == 'pp.' or item == 'p.':
                    next_element = li[li.index(item)+1]
                    pdf_name.append(next_element)
                    pdf_name = [x.split()[0] for x in pdf_name]
                if item == 'Front' or item == 'Back':
                    pdf_name.append(item)
                    pdf_name = [x.split()[0] for x in pdf_name]

for filename in os.listdir("."):
    if filename.endswith(".pdf"):
        for item in pdf_name:
            src = item + ".pdf"
            dst = filename
            os.rename(src, dst)

print(pdf_name)

But I'm getting this error message:

error message

Even though as you can see in the folder, 211-225.pdf and Front.pdf files have been already renamed successfully, but for the rest, I'm getting the aforementioned error above.

Upvotes: 0

Views: 256

Answers (2)

André
André

Reputation: 350

There are multiple issues with that code you posted.

for filename in os.listdir("."):
    if filename.endswith(".pdf"):
        for item in pdf_name:
            src = item + ".pdf"
            dst = filename
            os.rename(src, dst)

In this block you are trying to rename different source files to the same destination file that already exists. (i) I think you swapped src and dst, (ii) After you renamed a file it will have the new name, so you can't rename multiple times. You either have to copy or rethink your loops.

Upvotes: 0

Thomas
Thomas

Reputation: 181715

I think your code is renaming the same file multiple times (with the inner for item in pdf_name loop). After the first rename, the file obviously won't exist under its old name anymore.

Upvotes: 2

Related Questions