Python 文本对话框提示框:
messagebox.showinfo("提示","你好,我是提示框")
Python 文件夹选择框:
foldr_patch_new = filedialog.askdirectory() # 选择文件夹,路径保存于foldr_patch中
实际案例:
业务场景:同事需要移动所有二级文件夹到指定的目录,
问题点:如何让他自动弹出对话框提示,并且可以交互选中文件夹==>就找到了上面两个知识点,部分代码如下:
'''
@Author: Liang
@Date: 2020-07-19 13:20:16
@LastEditTime: 2020-07-19 16:43:06
@LastEditors: Please set LastEditors
@Description: 环境:Python3.8
@FilePath: /undefinedc:/Users/Downloads/test - 副本.py
'''
import time
from tkinter import filedialog
from tkinter import messagebox
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 移动文件
messagebox.showinfo("提示","请先选择需要处理的文件夹")
foldr_patch_old = filedialog.askdirectory() # 选择文件夹,路径保存于foldr_patch中
messagebox.showinfo("提示","请先选择需要移动到哪里")
foldr_patch_new = filedialog.askdirectory() # 选择文件夹,路径保存于foldr_patch中
if not foldr_patch_old or not foldr_patch_new:
print("foldr_patch_old",foldr_patch_old)
print("foldr_patch_new",foldr_patch_new)
print("路径为空,或者您没有选择正确的路径,请重新运行程序\n" * 100)
time.sleep(3)
exit()
if foldr_patch_old == foldr_patch_new:
print("您两次选择的路径是相同的,请核实")
'''
@Author: Liang
@Date: 2020-07-19 13:20:16
@LastEditTime: 2020-07-19 16:43:06
@LastEditors: Please set LastEditors
@Description: 选中文件夹路径,递归里面的所有二级文件夹,将其移动到一个指定的新的文件夹里,随后删除所有名字为5.jpg的,删除所有>=30.jpg的,重命名1.jpg 为 上层文件夹名字.jpg
@FilePath: /undefinedc:/Users/Downloads/test - 副本.py
'''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Python 3.8
import os
import glob
import time
import shutil
from tkinter import filedialog
from tkinter import messagebox
# 移动文件
messagebox.showinfo("提示","请先选择需要处理的文件夹")
foldr_patch_old = filedialog.askdirectory() # 选择文件夹,路径保存于foldr_patch中
messagebox.showinfo("提示","请先选择需要移动到哪里")
foldr_patch_new = filedialog.askdirectory() # 选择文件夹,路径保存于foldr_patch中
print(foldr_patch_old,foldr_patch_new)
if not foldr_patch_old or not foldr_patch_new:
print("路径为空,或者您没有选择正确的路径,请重新运行程序\n" * 100)
time.sleep(3)
exit()
if foldr_patch_old == foldr_patch_new:
print("您两次选择的路径是相同的,请核实并重新运行程序\n" * 100)
time.sleep(3)
exit()
for i in glob.glob(foldr_patch_old + '/**',recursive=True):
if os.path.isdir(i) == True and i.count("\\") == 2: # 二级文件夹 因为没有三级文件夹,所以不写 >=2
print(os.path.isdir(i)," ==> ", i)
shutil.move(i,foldr_patch_new)
# 移动完毕,处理内部文件
for i in os.listdir(foldr_patch_new):
# 重命名 将第一各文件,重命名为文件夹的名字
os.rename(os.path.join(foldr_patch_new,i,'1.jpg'),os.path.join(foldr_patch_new,i,i + '.jpg'))
# 检查是否有名字>30的,如果有,那么就删除掉
for k in range(30,1000):
if os.path.exists(os.path.join(foldr_patch_new,i,str(k) + '.jpg')) == True:
print(os.path.join(foldr_patch_new,i,str(k) + '.jpg'))
os.remove(os.path.join(foldr_patch_new,i,str(k) + '.jpg'))
# 检查是否有名字 == 5.jpg的,如果有,那么就删除掉
if os.path.exists(os.path.join(foldr_patch_new,i,'5.jpg')) == True:
os.remove(os.path.join(foldr_patch_new,i,'5.jpg'))
if os.path.exists(os.path.join(foldr_patch_new,i,'30.png')) == True:
os.remove(os.path.join(foldr_patch_new,i,'30.png'))
messagebox.showinfo("提示","你好,已完成")