4

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 ?

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)
UserAG
  • 132
  • 6
  • And https://stackoverflow.com/questions/9765227/ioerror-errno-2-no-such-file-or-directory-trying-to-open-a-file, and https://stackoverflow.com/questions/36477665/python-on-windows-ioerror-errno-2-no-such-file-or-directory – Ilja Everilä Aug 24 '17 at 05:57
  • Perhaps use `glob.glob('/home/pi/Downloads/test/*')` instead... – Antti Haapala Aug 24 '17 at 06:05

3 Answers3

7

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)
PRMoureu
  • 11,272
  • 6
  • 31
  • 41
2

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.

Simple fix:

for x in arr:
    with open(os.path.join(path, x), 'rb') as fh:
        …
duskwuff -inactive-
  • 171,163
  • 27
  • 219
  • 269
1

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(..)
Vivek Sable
  • 8,494
  • 3
  • 32
  • 45