person812949212442
person812949212442

Reputation: 3

Python File Renaming Issue

import os
for filename in os.listdir("."):
    if not filename.startswith("renamefilesindir"):
            for filename2 in os.listdir(filename):
                    if filename2.startswith("abcdefghij"):
                            newName = "[abcdefghij.com][abcde fghij][" + filename + "][" + filename2[11:16] + "].jpg"
                            print(filename2)
                            print(newName)
                            os.rename(filename2, newName)

I have a folder with a few hundred other folders inside of it. Inside each secondary folder is a number of files all similarly named. What I want to do is rename each file, but I get the following error whenever I run the above program.

abcdefghij_88741-lg.jpg
[abcdefghij.com][abcde fghij][3750][88741].jpg
Traceback (most recent call last):
  File "C:\directory\renamefilesindir.py", line 9, in <module>
    os.rename(filename2, newName)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'abcdefghij_88741-lg.jpg' -> '[abcdefghij.com][abcde fghij][3750][88741].jpg'

I don't know what this means. It prints the existing file name, so I know it's found the file to be changed. Am I renaming the file wrong? What can't it find?

Upvotes: 0

Views: 278

Answers (1)

JuniorCompressor
JuniorCompressor

Reputation: 20015

os.listdir contains just the names of the files and not the full paths. That's why your program actually tried to rename a file inside your current directory and it failed. So you could do the following:

import os.path
os.rename(os.path.join(filename, filename2), os.path.join(filename, newName))

since file with name filename2 is inside directory with name filename.

Upvotes: 1

Related Questions