1 Star 0 Fork 0

匹诺曹/my_util

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
win_move_parent_all_file_folder.py 2.22 KB
一键复制 编辑 原始数据 按行查看 历史
匹诺曹 提交于 2024-11-13 10:54 . update
import os
import shutil
directory = 'D:\\test\\'
def move_folder_to_parent(folder_name):
# 获取当前文件夹的绝对路径
current_path = os.path.abspath(folder_name)
# 获取上上一级目录的路径
destination_path = os.path.abspath(os.path.join(current_path, "../.."))
# 第二次检查目标文件夹是否存在,避免覆盖
target_path = os.path.join(destination_path, os.path.basename(current_path))
if not os.path.exists(target_path):
# 移动文件夹
shutil.move(current_path, target_path)
print(f"文件夹已成功移动到:{target_path}")
else:
print(f"目标路径 {target_path} 已存在,移动失败。")
def del_empty_folder(folder_name):
if os.path.isdir(folder_name):
if os.path.isdir(file_path):
if os.listdir(folder_name) != []:
for filename in os.listdir(folder_name):
child_file_path = os.path.join(folder_name, filename)
del_empty_folder(child_file_path)
else:
shutil.rmtree(folder_name)
# 列出目录下的所有文件和文件夹
for filename in os.listdir(directory):
file_path = os.path.join(os.path.abspath(directory), filename)
if os.path.isdir(file_path):
for child_filename in os.listdir(file_path):
childPath = os.path.join(os.path.abspath(file_path), child_filename)
if os.path.isdir(childPath):
for child_child_filename in os.listdir(childPath):
childChildPath = os.path.join(os.path.abspath(childPath), child_child_filename)
if os.path.isdir(childChildPath):
move_folder_to_parent(childChildPath)
if os.path.isfile(childChildPath):
destination_path = os.path.abspath(os.path.join(childChildPath, "../.."))
target_path = os.path.join(destination_path, child_child_filename)
if not os.path.exists(target_path):
shutil.move(childChildPath, destination_path)
else:
print(f"目标路径 {target_path} 已存在,移动失败。")
del_empty_folder(directory)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guwei786228836/my_util.git
[email protected]:guwei786228836/my_util.git
guwei786228836
my_util
my_util
master

搜索帮助