Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

rename - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...