[英]IOError: [Errno 2] No such file or directory – os.walk
I'm trying to run the following script which simply reads and image and saves it again:我正在尝试运行以下脚本,它只是读取和图像并再次保存它:
from PIL import Image
import os
rootdir = '/home/user/Desktop/sample'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
im = Image.open(file)
im.save(file)
I however get the following error:但是,我收到以下错误:
Traceback (most recent call last):
File "test.py", line 10, in <module>
im = Image.open(file)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2258, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 2] No such file or directory: '1.jpg'
So, what I'm trying to do is simply read the file 1.jpg
and save it again, provided that 1.jpg
is located in the directory.所以,我要做的只是读取文件
1.jpg
并再次保存,前提是1.jpg
位于目录中。
How can I fix this issue?我该如何解决这个问题?
Thanks.谢谢。
You're going to need to provide a fully qualified path, because file
holds only the tail, not the entire path.您将需要提供一个完全限定的路径,因为
file
只包含尾部,而不是整个路径。
You can use os.path.join
to join the root
to the tail:您可以使用
os.path.join
将root
连接到尾部:
for root, dirs, files in os.walk(rootdir):
for file in files:
path = os.path.join(root, file)
im = Image.open(path)
im.save(path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.