[英]'FileNotFoundError: [Errno 2] No such file or directory' when trying to convert images in directory from JPG to PNG files
I am new to Python, and I am trying to convert all images in my file (JPG) to PNG format.我是 Python 新手,我正在尝试将我的文件 (JPG) 中的所有图像转换为 PNG 格式。
I am using this code:我正在使用此代码:
from PIL import Image
import os
#Image directory
directory = "D:\\weeds"
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
However, the following error is generated:但是,会生成以下错误:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-26-871d84dccfb2> in <module>
7 if filename.endswith(".jpg"):
8 prefix = filename.split(".jpg")[0]
----> 9 im = Image.open(filename)
10 im.save(prefix+'.png')
11 else:
~\lib\site-packages\PIL\Image.py in open(fp, mode)
2876
2877 if filename:
-> 2878 fp = builtins.open(filename, "rb")
2879 exclusive_fp = True
2880
FileNotFoundError: [Errno 2] No such file or directory: 'weed0.jpg'
This image is clearly in my directory:这张图片显然在我的目录中:
How can I fix this error, and convert all JPG images to PNG?如何修复此错误,并将所有 JPG 图像转换为 PNG?
The problem is os.listdir
gives you the leaf file names.问题是os.listdir
为您提供叶文件名。 It does not give you the full paths.它没有给你完整的路径。 For example, in your case, the directory is "D:\\\\weeds"
, so any results from os.listdir
would give you names such "foo"
or "bar"
but not "D:\\\\weeds\\foo"
.例如,在您的情况下,目录是"D:\\\\weeds"
,因此os.listdir
任何结果都会为您提供诸如"foo"
或"bar"
名称,而不是"D:\\\\weeds\\foo"
。 In order to use the results of os.listdir
from any working directory, you need to use os.path.join
with "D:\\\\weeds"
to form the full, correct path.为了使用来自任何工作目录的os.listdir
的结果,您需要使用os.path.join
和"D:\\\\weeds"
来形成完整、正确的路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.