IOError: [Errno 2] No such file or directory (文件实际存在) Python

8
我正在研究如何通过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)

和 https://dev59.com/Ymkw5IYBdhLWcg3wm74h,以及 https://dev59.com/B5Xfa4cB1Zd3GeqPk9ck - Ilja Everilä
也许可以使用 glob.glob('/home/pi/Downloads/test/*') 来代替... - Antti Haapala -- Слава Україні
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) 返回给定路径下文件和文件夹的名称列表,但不包括完整路径。

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

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

Documentation:

  1. os.listdir(..)
  2. os.path.join(..)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接