Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

python - 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.

How can I fix this issue?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...