FileNotFoundError: [Errno 2] No such file or directory: '/tmp/cats-v-dog

Viewed 3929

I create some directories using os.mkdir

try:
#YOUR CODE GOES HERE
os.mkdir("/tmp/cats-v-dogs/")
os.mkdir("/tmp/cats-v-dogs/training/cats")
os.mkdir('/tmp/cats-v-dogs/training/dogs/')
os.mkdir('/tmp/cats-v-dogs/testing/cats')
os.mkdir('/tmp/cats-v-dogs/testing/dogs')
except OSError:
pass

I have list: training =[dog1,dog2,...,dog100] TRAINING_DOGS_DIR = "/tmp/cats-v-dogs/training/cats/" I want to copy a file from one directory to another one using trainig element:

for list1 in training:
copyfile(os.path.join(SOURCE,list1),TRAINING_DOGS_DIR)

After I run that loop this is the error I get:

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/cats-v-dogs/training/dogs/'

Some help or suggestion thanks/

2 Answers

The try-except block is what's hurting you here. os.mkdir is only able to make a single directory at a time depth-wise, so your second through fifth lines are all failing, but because you're catching the exception the error is correct.

Solution: replace all of the os.mkdir with os.makedirs which will create all of these without an issue. And get rid of the try-except! Those should only be used when you know exactly what you're catching.

You can use os.makedirs which includes an exist_ok parameter:

os.makedirs("/tmp/cats-v-dogs/", exist_ok=True)
Related