Python 重命名程序中的错误......没有这样的文件或目录(Fnmatch) [英] Bug in Python Renaming Program.....No such file or Directory (Fnmatch)

查看:36
本文介绍了Python 重命名程序中的错误......没有这样的文件或目录(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.

代码如下:

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

我也试过这个:

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)

os.path.join 函数 使用适合您平台的正确目录分隔符,智能地将路径元素连接成一个整体.

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

这篇关于Python 重命名程序中的错误......没有这样的文件或目录(Fnmatch)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆