简体   繁体   English

在Python中重命名文件:无此类文件或目录

[英]Renaming files in Python: No such file or directory

If I try to rename files in a directory, for some reason I get an error. 如果我尝试重命名目录中的文件,由于某种原因,我会收到错误消息。 I think the problem may be that I have not inserted the directory in the proper format ? 我认为问题可能是我没有以正确的格式插入目录?

Additional info: python 2 & linux machine 附加信息:python 2和linux机器

OSError: [Errno 2] No such file or directory OSError:[Errno 2]没有这样的文件或目录

Though it prints the directories content just fine. 尽管它可以打印目录内容。 What am I doing wrong? 我究竟做错了什么?

import os

for i in os.listdir("/home/fanna/Videos/strange"):
    #print str(i)
    os.rename(i, i[:-17])

os.rename() is expecting the full path to the file you want to rename. os.rename()需要您要重命名的文件的完整路径。 os.listdir only returns the filenames in the directory. os.listdir仅返回目录中的文件名。 Try this 尝试这个

import os
baseDir = "/home/fanna/Videos/strange/"
for i in os.listdir( baseDir ):
    os.rename( baseDir + i, baseDir + i[:-17] )

Suppose there is a file /home/fanna/Videos/strange/name_of_some_video_file.avi , and you're running the script from /home/fanna . 假设有一个文件/home/fanna/Videos/strange/name_of_some_video_file.avi ,并且您正在/home/fanna运行脚本。

i is name_of_some_video_file.avi (the name of the file, not including the full path to it). iname_of_some_video_file.avi (文件名,不包括文件的完整路径)。 So when you run 所以当你跑步

os.rename(i, i[:-17])

you're saying 你是说

os.rename("name_of_some_video_file.avi", "name_of_some_video_file.avi"[:-17])

Python has no idea that these files came from /home/fanna/Videos/strange . Python不知道这些文件来自/home/fanna/Videos/strange It resolves them against the currrent working directory, so it's looking for /home/fanna/name_of_some_video_file.avi . 它根据当前工作目录解析它们,因此它正在寻找/home/fanna/name_of_some_video_file.avi

I'm a little late but the reason it happens is that os.listdir only lists the items inside that directory, but the working directory remains the location where the python script is located. 我有点晚了,但是发生的原因是os.listdir仅列出了该目录中的项目,但是工作目录仍然是python脚本所在的位置。

So to fix the issue add: 因此,要解决此问题,请添加:

os.chdir(your_directory_here)

just before the for loop where your_directory_here is the directory you used for os.listdir . 就在for循环之前,其中your_directory_here是用于os.listdir的目录。

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

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