简体   繁体   中英

Bug in Python Renaming Program…No such file or Directory (Fnmatch)

I'm trying to build a little renaming program to help save me time in the future. Basically it will go through directories I point it too and rename files if they meet certain criteria.

I have written what I need but I have a bug in the very beginning that I can't figure out.

Here is the code:

import os
import fnmatch

for file in os.listdir("""/Users/Desktop/TESTME"""):
    if fnmatch.fnmatch(file,'MISC*'):
        os.rename(file, file[4:12] + '-13-Misc.jpg')

When I try to run it I am getting this:

Traceback (most recent call last):
  File "/Users/Documents/Try.py", line 6, in <module>
    os.rename(file, file[4:12] + '-13-Misc.jpg')
OSError: [Errno 2] No such file or directory

I also tried this:

if fnmatch.fnmatch(file,'MISC*'):
    fun = file[4:12] + '-13-Misc.jpg'
    os.rename(file, fun)

But I get the same thing.

It's not recognizing the file as a file. Am I going about this the wrong way?

You'll need to include the full path to the filenames you are trying to rename:

import os
import fnmatch

directory = "/Users/Desktop/TESTME"
for file in os.listdir(directory):
    if fnmatch.fnmatch(file, 'MISC*'):
        path = os.path.join(directory, file)
        target = os.path.join(directory, file[4:12] + '-13-Misc.jpg'
        os.rename(path, target)

The os.path.join function intelligently joins path elements into a whole, using the correct directory separator for your platform.

The function os.listdir() only returns the file names of the files in the given directory, not their full paths. You can use os.path.join(directory, file_name) to reconstruct the full path of the file.

You could also do this in bash:

cd /Users/Desktop/TESTME/
for f in MISC*; do mv "$f" "${f:4:8}-13-Misc.jpg"; done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM