IOError:[Errno 2]没有这样的文件或目录(当它确实存在时)Python [英] IOError: [Errno 2] No such file or directory (when it really exist) Python

查看:119
本文介绍了IOError:[Errno 2]没有这样的文件或目录(当它确实存在时)Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过python中的uart处理文件的传输文件夹.在下面您可以看到简单的功能,但是有一个问题,因为出现标题中所示的错误:IOError: [Errno 2] No such file or directory: '1.jpg'其中1.jpg是测试文件夹中的文件之一.因此,这很奇怪,因为程序知道不存在的文件名吗?我在做什么错了?

I'm working on transfer folder of files via uart in python. Below you see simple function, but there is a problem because I get error like in title : IOError: [Errno 2] No such file or directory: '1.jpg' where 1.jpg is one of the files in test folder. So it is quite strange because program know file name which for it doesn't exist ?! What I'm doing wrong ?

def send2():
    path = '/home/pi/Downloads/test/'
    arr = os.listdir(path)
    for x in arr:
        with open(x, 'rb') as fh:
            while True:
                # send in 1024byte parts
                chunk = fh.read(1024)
                if not chunk: break
                ser.write(chunk)

推荐答案

如果您要打开的文件不在您的工作目录中,则需要提供它们的实际完整路径:

You need to provide the actual full path of the files you want to open if they are not in your working directory :

import os
def send2():
    path = '/home/pi/Downloads/test/'
    arr = os.listdir(path)
    for x in arr:
        xpath = os.path.join(path,x)
        with open(xpath, 'rb') as fh:
            while True:
                # send in 1024byte parts
                chunk = fh.read(1024)
                if not chunk: break
                ser.write(chunk)

这篇关于IOError:[Errno 2]没有这样的文件或目录(当它确实存在时)Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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