简体   繁体   English

有人可以帮助我解决 FileNotFoundError python

[英]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.我正在尝试将文件从一个文件夹复制到另一个文件夹,所以我首先创建了 2 个文件夹和子文件夹,但是当我尝试使用 shutil.copyfile() 复制文件时出现问题,问题是当我运行此代码时在我的文件夹路径的末尾添加了一个斜杠(/)。 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.我正在使用谷歌 colab。

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.使用pathlib将父文件夹创建到最终文件夹,并避免错误。 Instead of using os.mkdir() .而不是使用os.mkdir()
  3. (Optional) Use raw string literal , by adding an r before a path string to escape backslash. (可选)使用原始字符串文字,通过在路径字符串前添加r来转义反斜杠。 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)

I think you need to mention drive name some think like 'Z:\Users\Jonathan\Documents\datas'我认为您需要提及驱动器名称,例如'Z:\ Users \ Jonathan \ Documents \ datas'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM