IOError:[Errno 2]没有这样的文件或目录– os.walk [英] IOError: [Errno 2] No such file or directory – os.walk

查看:84
本文介绍了IOError:[Errno 2]没有这样的文件或目录– 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)

但是我得到以下错误:

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'

因此,只要1.jpg位于目录中,我想做的就是简单地读取文件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.

如何解决此问题?

谢谢.

推荐答案

您将需要提供一个完全限定的路径,因为file仅保留尾部,而不包含整个路径.

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

您可以使用os.path.joinroot连接到尾部:

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)

这篇关于IOError:[Errno 2]没有这样的文件或目录– os.walk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆