python - 如何将一个文件相应地复制到一个文件夹中?
问题描述
我想制作一个可以将一个文件(例如图像)复制到另一个包含多个文件夹的目录的程序。通过将所有图像复制到另一个目录很容易,但我希望它是一个图像复制到一个文件夹。
我循环了两个目录中的每个元素并将它们全球化。我尝试将一个文件复制到文件夹中,但出现错误。我认为我无法做到的主要问题是因为我不知道如何在循环时将一个文件复制到一个文件夹。我希望你能给我一些关于这个问题的建议。
import os
import shutil
path = os.listdir('C:\\Users\\User\\Desktop\\img')
#dst1 = os.path.abspath('C:\\Users\\User\\Desktop\\abc')
idst = os.listdir('C:\\Users\\User\\Desktop\\abc')
def allimgs():
counter = 0
for imgs in path:
if imgs.endswith('.JPG'):
counter += 1
#if hits the 24th images then stop and
#copy the first until 24 to another 24 folders one by one
if counter > 24:
break
else:
src = os.path.join('C:\\Users\\User\\Desktop\\img',imgs)
def allfolders():
for folders in idst:
if folders.endswith('.db'):
continue #to skip the file ends with .db
dst = os.path.join('C:\\Users\\User\\Desktop\\abc',folders)
shutil.copy(allimgs(),allfolders()) #here is where i stuck
解决方案
首先,让这两个函数返回字符串列表,其中包含将被复制的图像的完整路径,以及将被复制到的目录。然后,将 和 的结果保存到变量中allimgs()
并allfolders()
循环遍历它们。
这是第一个函数的样子:
def allimgs():
ret = []
counter = 0
for imgs in path:
if imgs.endswith('.JPG'):
counter += 1
#if hits the 24th images then stop and
#copy the first until 24 to another 24 folders one by one
if counter > 24:
break
else:
src = os.path.join('C:\\Users\\User\\Desktop\\img',imgs)
ret.append(src)
return ret
(我把另一个留给你作为练习)
然后遍历它们:
for image_path in allimgs():
for folder_path in allfolders():
shutil.copy(image_path, folder_path)
推荐阅读
- python - Python Selenium 多线程处理不同的 Chrome 实例
- java - Java UTF-8 格式错误的测试用例是对的吗?
- ios - 更改数组中的值
- java - 在 java 中发送字节时出错:缓冲读取器和输入流
- acumatica - Acumata Web 服务端点添加供应商位置
- sql - 如何在sql中的表中按ID填充缺失的日期
- react-native - 将 Base64 转换为 png 并保存在设备 React Native Expo 中
- java - 在java中返回一个子类类型
- r - 如果其他逻辑与常量变量一起使用,r 栅格无法获得
- laravel - Vuex 从 laravel 检索数据