我正在通过 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)
如果要打开的文件不在您的工作目录中,您需要提供它们的实际完整路径:
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)
os.listdir()
仅返回裸文件名,而不是完全限定的路径。这些文件(可能?)不在您当前的工作目录中,因此错误消息是正确的 - 这些文件不存在于您要查找的位置。
简单修复:
for x in arr:
with open(os.path.join(path, x), 'rb') as fh:
…
是,代码引发错误,因为您正在打开的文件不存在于运行Python代码的当前位置。
os.listdir(path)
返回给定位置的文件和文件夹名称列表,而不是完整路径。
使用
os.path.join()
在 for
循环中创建完整路径。
例如
file_path = os.path.join(path, x)
with open(file_path, 'rb') as fh:
.....
文档: