【问题标题】:Move files from subfolders to another folder将文件从子文件夹移动到另一个文件夹
【发布时间】:2022-10-25 23:41:07
【问题描述】:

我想将所有文件从多个子目录移动到与父文件夹位于同一目录中的另一个文件夹,但出现以下错误:

FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_0001.jpg' -> '/content/drive/MyDrive/Dev/FaceRec/negatives/Emmit_Smith_0001.jpg'

这是我的代码:

for directory in os.listdir('/content/drive/MyDrive/Dev/FaceRec/lfw'):
  for file in os.listdir(os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory)):
    path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/lfw', directory, file)
    new_path = os.path.join('/content/drive/MyDrive/Dev/FaceRec/negatives', file)
    os.replace(path, new_path)

提前感谢您的帮助

【问题讨论】:

  • /content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_0001.jpg 是链接吗?
  • 是的,它是其中一个子文件夹中的文件(抱歉花了一段时间才找到它)
  • 目录/content/drive/MyDrive/Dev/FaceRec/negatives 是否存在?
  • @Cuartero 是的,它存在于其中,它们都位于 FaceRec

标签: python


【解决方案1】:

尝试以下操作:

import os
import glob

src_path = '/content/drive/MyDrive/Dev/FaceRec/lfw'
dest_path = src_path.replace('lfw', 'negatives')
flist = glob.glob(os.path.join(src_path, '*/*'))
for fname in flist:
    shutil.move(fname, fname.replace(os.path.dirname(fname), dest_path))

为什么这更好:

  1. glob 函数有助于避免一个 for 循环,还可以防止重复将路径连接在一起
  2. shutil.move为您创建目标目录(如果它不存在)。它还可以处理符号链接。
  3. 通过将路径放入变量中,我们可以最大限度地减少复制过去的错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    相关资源
    最近更新 更多