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

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

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)

os.listdir() just returns bare filenames, not fully qualified paths. These files (probably?) arent in your current working directory, so the error message is correct — the files dont exist in the place youre looking for them.

Simple fix:

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

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

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

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

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

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

Documentation:

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

Leave a Reply

Your email address will not be published.