gpt4 book ai didi

python - 将批图像文件从子文件夹复制到父文件夹

转载 作者:行者123 更新时间:2023-12-03 08:04:11 24 4
gpt4 key购买 nike

在一个目录下有几个文件夹,其名称如下:301、302、...、600。每个文件夹都包含两个文件夹,名称分别为 AB。我需要将所有图像文件从每个父文件夹的 A 文件夹复制到该文件夹​​的环境(将图像文件从例如 600>A 复制到 600 文件夹),然后删除 AB每个父文件夹的 文件夹。我从this post找到了解决方案但我不知道如何将文件复制到父文件夹而不是子文件夹中,也不知道如何在复制多个文件夹并执行此操作后删除子文件夹。

import shutil
import os, sys

exepath = sys.argv[0]

directory = os.path.dirname(os.path.abspath(exepath))+"\\Files\\"

credit_folder = os.path.dirname(os.path.abspath(exepath))+"\\Credits\\"

os.chdir(credit_folder)
os.chdir(directory)

Source = credit_folder
Target = directory

files = os.listdir(Source)
folders = os.listdir(Target)

for file in files:
SourceCredits = os.path.join(Source,file)

for folder in folders:
TargetFolder = os.path.join(Target,folder)

shutil.copy2(SourceCredits, TargetFolder)
print(" \n ===> Credits Copy & Paste Sucessfully <=== \n ")

最佳答案

@hellohawii 给出了很好的答案。以下代码也有效,使用时只需更改 Source 的值即可。

import shutil
import os, sys
from tqdm import tqdm

exepath = sys.argv[0] # current path of code

Source = os.path.dirname(os.path.abspath(exepath))+"\\Credits\\" # path of folders:301, 302... 600

# Source = your_path_of_folders

files = os.listdir(Source) # get list of folders under 301 etc, in your situation: [A, B]


def get_parent_dir(path=None, offset=-1):
"""get parent dir of current path"""
result = path if path else __file__
for i in range(abs(offset)):
result = os.path.dirname(result)
return result


def del_files0(dir_path):
"""delete full folder"""
shutil.rmtree(dir_path)


for file_path in files:
current_path = os.path.join(Source, file_path) # current_path
if file_path == 'A': # select the folder to copy
file_list = os.listdir(current_path) # get file_list of selected folder
parent_path = get_parent_dir(current_path) # get parent dir path, namely target path
for file in tqdm(file_list):
shutil.copy(file, parent_path)
del_files0(current_path) # delete current path(folder)
print(" \n ===> Credits Copy & Paste & delete Successfully <=== \n ")

关于python - 将批图像文件从子文件夹复制到父文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72944672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com