在文本文件中写入要生成的文件夹清单,然后选择文本文件,根据文本文件的内容生成文件夹。
import tkinter
import tkinter.filedialog
import tkinter.messagebox
import os
root = tkinter.Tk()
root.title("tkinter生成项目文件夹")
width = 700
height = 500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
root.geometry(alignstr)
def choosefile():
b =tkinter.filedialog.askopenfilename()
#print(b)
a=b[b.rfind("/")+1:]#返回文件名
#print(a)
listbox_file.insert(0,a)
return a
def createdir():
fieselected=choosefile()
filetype=os.path.splitext(fieselected)[1]
print(filetype)
path=fieselected[:-4] # 要创建文件夹的路径
if not filetype==".txt":
tkinter.messagebox.showwarning('警告', "请选择文本文件")
else:
if not os.path.exists(path):
os.mkdir(path)
else:
tkinter.messagebox.showwarning('警告', "文件夹已存在")
with open(fieselected,'r',encoding='utf-8') as f:
for line in f.readlines(): # 读取所有行
dirpath=path+'\\'+line.strip() # 拼接要创建的文件夹路径
if not os.path.exists(dirpath): # 判断路径不存在
os.mkdir(dirpath) # 创建文件夹
print(dirpath)
print('创建完成……')
os.startfile(path) # 打开路径
listbox_file=tkinter.Listbox(root,justify=tkinter.LEFT)
listbox_file.place(relx=0.0,rely=0.05,relwidth=0.5,height=20)
buttonfile=tkinter.Button(root,text="选择文件",command=createdir)
buttonfile.place(relx=0.5,rely=0.05,width=100,height=20)
tkinter.mainloop()