[英]Copying multiple images in a list from one folder to another without copying all images
[英]File not found error when copying images from one folder to another
我有一個文本文件,其中包含要從源文件夾復制到目標文件夾的圖像名稱。 源文件夾包含幾個子文件夾,如下所示。 圖像可能來自這些子文件夾中的任何一個。
animals (source folder)
|-cats_1
|-cats_2
|-tigers_1
|-lions_1
|-lions_2
下面顯示的是Python代碼:
import os
import shutil
src = r'X:\animals' #source with multiple sub-folders
dest = r'X:\images\cat_family' #destination folder
with open('cat_fam.txt') as file: #text file containing the image names
for path, subdirs, files in os.walk(src):
for name in file:
file_name = name.strip()
filename = os.path.join(path, file_name)
shutil.copy2(filename, dest)
我遇到一個文件未找到的錯誤,如下所示:
File "C:\Users\AppData\Local\Temp\2/ipykernel_30556/2100413787.py", line 6, in <module>
shutil.copy2(filename, dest)
File "C:\Users\AppData\Local\Continuum\anaconda3\envs\tf2.7\lib\shutil.py", line 266, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\AppData\Local\Continuum\anaconda3\envs\tf2.7\lib\shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'X:\\animals\\lion_2345.jpg'
一種方法是根據 os.walk() 返回的數據構建字典
字典將以文件名(而不是完整路徑)為關鍵字,其值將是文件所在的目錄。
然后你可以閱讀 cat_fam.txt 文件並在字典中查找以查看它存在的位置(如果它存在!)
from os.path import join
from os import walk
from shutil import copy2
src = r'X:\animals'
dest = r'X:\animals\cat_family'
db = dict()
for root, _, files in walk(src):
for file in files:
db[file] = root
with open('cat_fam.txt') as fam:
for cat in map(str.strip, fam):
fp = db.get(cat)
if fp is not None:
copy2(join(fp, cat), join(dest, cat))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.