gpt4 book ai didi

python - 将文件递归移动到新目录shutil.move

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:01 26 4
gpt4 key购买 nike

我正在尝试将所有.jpg 文件以递归方式从CWD 移动到一个新目录中。无法使 shutil.move 递归。关于代码最后一行有什么提示吗?

import glob
import shutil
import os

from_dir = input('Enter recursive FROM directory (if CWD, enter .): ')
to_dir = input('Enter TO directory (if CWD, enter .): ')

if not os.path.exists(to_dir):
os.makedirs(to_dir)

for imagfile in glob.iglob(os.path.join(from_dir, "*.jpg")):
shutil.move(imagfile, to_dir)

我尝试了这些,不起作用:

#shutil.move(os.path.join(root, imagfile), os.path.join(to_dir, imagfile))
#shutil.move(from_dir, imagfile, to_dir)
#shutil.move(os.path.join(from_dir, imagfile), to_dir)
#shutil.move(imagfile, to_dir+imagfile)
#shutil.move(from_dir+imagfile, to_dir+imagfile)

最佳答案

试试这个:

import os, time, inspect, shutil

main_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

from_dir = "" # write your source dir
to_dir = "" # write your target dir


def check_target():

global to_dir

if to_dir.strip() == "":
print("Plz Insert a Valid 'to_dir' path!")
exit()

elif to_dir == ".":
to_dir = os.path.join(main_path, to_dir)

elif os.path.exists(to_dir) is True:
to_dir = os.path.abspath(to_dir)

else:
os.mkdir(to_dir)


check_target()


for dirpath, _, filenames in os.walk(from_dir):

for items in filenames:

file_full_path = os.path.abspath(os.path.join(dirpath, items))

if file_full_path.lower().endswith(".jpg") or file_full_path.lower().endswith(".jpeg"):

check_address = os.path.join(to_dir, os.path.basename(file_full_path))

if os.path.exists(check_address) and os.path.isfile(check_address):

warning_message = "WARNING Duplicate File Names : {0}".format(check_address)
print(warning_message)

else:
try:
shutil.move(file_full_path, check_address)
except:
print("Something Went Wrong On " + file_full_path)

else:
pass

祝你好运...

关于python - 将文件递归移动到新目录shutil.move,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148519/

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