简体   繁体   English

Python重命名程序中的错误...没有这样的文件或目录(Fnmatch)

[英]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. os.path.join函数使用您平台的正确目录分隔符智能地将路径元素连接成一个整体。

The function os.listdir() only returns the file names of the files in the given directory, not their full paths. 函数os.listdir()仅返回给定目录中文件的文件名,而不是它们的完整路径。 You can use os.path.join(directory, file_name) to reconstruct the full path of the file. 您可以使用os.path.join(directory, file_name)来重建文件的完整路径。

You could also do this in bash: 您也可以在bash中执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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