Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...