IOError:[Errno 2]没有这样的文件或目录(当它确实存在时)Python [重复]

问题描述 投票:0回答:3

我正在通过 python 中的 uart 传输文件文件夹。下面您可以看到简单的功能,但有一个问题,因为我收到如标题所示的错误:

IOError: [Errno 2] No such file or directory: '1.jpg'
,其中 1.jpg 是测试文件夹中的文件之一。所以这很奇怪,因为程序知道它不存在的文件名?!我做错了什么?

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)
python file-transfer uart errno
3个回答
11
投票

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

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)

2
投票

os.listdir()
仅返回裸文件名,而不是完全限定的路径。这些文件(可能?)不在您当前的工作目录中,因此错误消息是正确的 - 这些文件不存在于您要查找的位置。

简单修复:

for x in arr:
    with open(os.path.join(path, x), 'rb') as fh:
        …

2
投票

,代码引发错误,因为您正在打开的文件不存在于运行Python代码的当前位置。

os.listdir(path)
返回给定位置的文件和文件夹名称列表,而不是完整路径。

使用

os.path.join()
for
循环中创建完整路径。 例如

file_path = os.path.join(path, x)
with open(file_path, 'rb') as fh:
       .....

文档:

  1. os.listdir(..)
  2. os.path.join(..)
© www.soinside.com 2019 - 2024. All rights reserved.