0

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.

2 Answers2

2

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)
hlin03
  • 125
  • 7
0

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

Bhar Jay
  • 184
  • 8
  • i've tried it also, but i had the same error – Alhaji Balla Fofanah Aug 04 '22 at 10:33
  • Try with both single and double front and back slash. in some cases the program location and file should be in same location – Bhar Jay Aug 04 '22 at 10:40
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 05 '22 at 21:03