IOError: [Errno 2] No such file or directory – os.walk

ぐ巨炮叔叔 提交于 2020-01-30 10:54:25

问题


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.

How can I fix this issue?

Thanks.


回答1:


You're going to need to provide a fully qualified path, because file holds only the tail, not the entire path.

You can use os.path.join to join the root to the tail:

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)


来源:https://stackoverflow.com/questions/45895813/ioerror-errno-2-no-such-file-or-directory-os-walk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!