someone can help me with FileNotFoundError python

i'm trying to copy files from one folder to another, so i've start by creating the 2 folder and subfolder but the problem occured when i tried to copy file using shutil.copyfile(), the problem is when i run this code one slash(/) is added tho the end of my folder path. find down my code.

original = 'Users\\Jonathan\\Documents\\datas'
base_direct = 'Users\\Jonathan\\Documents\\dataset'
os.mkdir(base_direct)
train_dir = os.path.join(base_direct, 'train')
os.mkdir(train_dir)
train_cats_dir = os.path.join(train_dir, 'cats')
os.mkdir(train_cats_dir)
fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]
for fname in fnames:
  src = os.path.join(original, fname)
  dst = os.path.join(train_cats_dir, fname)
  shutil.copyfile(src, dst)

so the error is saying:

FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Jonathan\\Documents\\datas/cat.0.jpg'

the problem is on the slash between datas and cat

i'm using google colab.

Upvotes: 0

Views: 114

Answers (2)

HL03
HL03

Reputation: 178

Recommend:

  1. Use absolute path, which should include a drive.
  2. Use pathlib to create the parent folders to the final folder, and avoid errors. Instead of using os.mkdir().
  3. (Optional) Use raw string literal, by adding an r before a path string to escape backslash. Does the same thing as a double back-slash but is neater.

Full code

import os
from pathlib import Path
import shutil

original = r'C:\Users\Jonathan\Documents\datas' # assuming you are using C drive
base_direct = r'C:\Users\Jonathan\Documents\dataset'

Path(base_direct).mkdir(parents=True, exist_ok=True)

train_dir = os.path.join(base_direct, 'train')
Path(train_dir).mkdir(parents=True, exist_ok=True)

train_cats_dir = os.path.join(train_dir, 'cats')
Path(train_cats_dir).mkdir(parents=True, exist_ok=True)

fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]

for fname in fnames:
  src = os.path.join(original, fname)
  dst = os.path.join(train_cats_dir, fname)
  shutil.copyfile(src, dst)

Upvotes: 2

Bhar Jay
Bhar Jay

Reputation: 184

I think you need to mention drive name some think like 'Z:\Users\Jonathan\Documents\datas'

Upvotes: 0

Related Questions