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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45853881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:20:04  来源:igfitidea点击:

IOError: [Errno 2] No such file or directory (when it really exist) Python

pythonfile-transferuarterrno

提问by PRMoureu

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 ?

我正在通过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)

回答by PRMoureu

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)

回答by duskwuff -inactive-

os.listdir()just returns bare filenames, not fully qualified paths. These files (probably?) aren't in your current working directory, so the error message is correct -- the files don't exist in the place you're looking for them.

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

Simple fix:

简单的修复:

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

回答by Vivek Sable

Yes, code raise Error because file which you are opening is not present at current location from where python code is running.

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

os.listdir(path)returns list of names of files and folders from given location, not full path.

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

use os.path.join()to create full path in forloop. e.g.

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

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

Documentation:

文档:

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