[英]Python says it can't find the file I am trying to rename even though it can read the file name
Im tryin to append a short string to every '.png' file.我试图在每个“.png”文件中附加一个短字符串。 But when I run it, it says cannot find the file.
但是当我运行它时,它说找不到文件。 But I know it's there and I can see it in the folder.
但我知道它在那里,我可以在文件夹中看到它。
Is there anything I need to do?有什么我需要做的吗?
Here is my script:这是我的脚本:
import os
for file in os.listdir("./pics"):
if file.endswith(".png"):
newFileName = "{0}_{2}{1}".format(*os.path.splitext(file) + ("z4",))
os.rename(file, newFileName)
Here is the error message I get...02.png is the first file in the folder:这是我收到的错误消息...02.png 是文件夹中的第一个文件:
fileNotFoundError: [WinError 2] The system cannot find the file specified: '02.png' -> '02_z4.png'
fileNotFoundError: [WinError 2] 系统找不到指定的文件:'02.png' -> '02_z4.png'
It's odd though because it gets the filename, in this case, 02.png
.不过这很奇怪,因为它获取了文件名,在本例中为
02.png
。 So if it can read the file name, why can't it find it?那么如果它可以读取文件名,为什么找不到它呢?
Thanks!谢谢!
I thought my comment might be enough, but for clarity I'll provide a short answer.我认为我的评论可能已经足够了,但为了清楚起见,我将提供一个简短的答案。
02.png
doesn't exist relative to your working directory. 02.png
相对于您的工作目录不存在。 You need to specify the path to the file for os.rename
so you need to include the directory.您需要为
os.rename
指定文件的路径,因此您需要包含该目录。
import os
for file in os.listdir("./pics"):
if file.endswith(".png"):
newFileName = "/pics/{0}_{2}{1}".format(*os.path.splitext(file) + ("z4",)) # Notice the ./pics
os.rename(os.path.join('pics', file), newFileName)
The name returned from os.listdir() gives the filename, not the full path.从 os.listdir() 返回的名称给出了文件名,而不是完整路径。 So you need to rename pics/02.png to pics/02_zf.png.
所以你需要将 pics/02.png 重命名为 pics/02_zf.png。 Right now you don't include the directory name.
现在您不包括目录名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.