我正在尝试将所有.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)
答案 0 :(得分:0)
也许你可以递归获取所有目录并使shutil.move到每个目录。
import os
root = "/Users/xyz/Documents/fun/test"
g = os.walk(root)
dirs = []
for i in g:
dirs.append(i[0])
print(dirs)
答案 1 :(得分:0)
试试这个:
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
祝你好运......