在工作中,我经常遇到一些纯人工活,比如把文件名登录到Excel里。但遇到100+以上的文件呢。。。emmmmmm一开始我是手动复制粘贴,然后就想用python写,这里记录一下编程的思路
根据Step1这个思路犹如把大象关进冰箱一样
不过具体实现还有很多的问题,例如遍历文件夹的时候是否要写入excel,文件名是否需要格式后缀,如果不需要该怎么办等等问题
经过百度大致确认了以下几个库
def get_folder(path): #这个函数是来分类文件夹和文件的
get_url = os.listdir(path)
for i in get_url:
sub_dir = os.path.join(path,i) # 把第一步获取的文件加入路径
if os.path.isdir(sub_dir): #如果当前仍然是文件夹,递归调用
print("正在检查%s"%sub_dir)
folder_name.append(sub_dir) #用folder_name来记录所有文件夹的路径
name.append(i)
get_folder(sub_dir)
用了一个递归调用,如果碰到文件夹就会一直检查,直到检查到文件。
然后用一个变量储存所有的文件夹的地址路径
def out_file(sheet,path,n,file_name): #这个函数是来写入文件名的
global index
get_name = os.listdir(path) #列出文件路径下的所有文件
print("正在写入"+path+"下的文件名称")
sheet.write_string(n,1,"文件名:")
sheet.write_url(n,2,path,string='文件夹名:'+file_name)
for i in get_name:
sub_dir = os.path.join(path,i)
if os.path.isdir(sub_dir): #如果是文件夹就继续循环
continue
else: #如果不是,就把文件名字写入表格中
sheet.write(n+1,0,index) #序号
sheet.write(n+1,1,i) #文件名(带格式)
sheet.write_url(n+1,2,sub_dir) #文件路径
n +=1
index +=1
return n+2
大体就完成了,就剩下参数设置和界面编辑我就略过了
import os
import re
import xlsxwriter
from tkinter import *
import time
def get_folder(path): #这个函数是来分类文件夹和文件的
get_url = os.listdir(path)
for i in get_url:
sub_dir = os.path.join(path,i) # 把第一步获取的文件加入路径
if os.path.isdir(sub_dir): #如果当前仍然是文件夹,递归调用
print("正在检查%s"%sub_dir)
folder_name.append(sub_dir) #用folder_name来记录所有文件夹的路径
name.append(i)
get_folder(sub_dir)
def out_file(sheet,path,n,file_name): #这个函数是来写入文件名的
global index
get_name = os.listdir(path) #列出文件路径下的所有文件
print("正在写入"+path+"下的文件名称")
sheet.write_string(n,1,"文件名:")
sheet.write_url(n,2,path,string='文件夹名:'+file_name)
for i in get_name:
sub_dir = os.path.join(path,i)
if os.path.isdir(sub_dir): #如果是文件夹就继续循环
continue
else: #如果不是,就把文件名字写入表格中
sheet.write(n+1,0,index) #序号
sheet.write(n+1,1,i) #文件名(带格式)
sheet.write_url(n+1,2,sub_dir) #文件路径
n +=1
index +=1
return n+2
def get(): #可以理解为主函数吧,主要是让tk调用
global folder_name,index,name
row = 0
folder_name =[]
index =1
name = []
xtime = time.localtime(time.time())
book = xlsxwriter.Workbook('auto_login'+str(xtime.tm_hour)+'.'+str(xtime.tm_min)+'.xlsx') #excel的命名与时间有关
sheet1 = book.add_worksheet('made by xiaoge') #sheet名字
path = path1.get() #从界面获取路径
folder_name.append(path)
name.append('源文件')
get_folder(path)
n = len(folder_name)
for i in range(n):
row = out_file(sheet1,folder_name[i],row,name[i]) #不停调用excel的写入文件名的函数
print("\n写入成功!!")
book.close()
root = Tk()
Lb1 = Label(root,text="请输入路径:").grid(row=0,column=0)
path1 = Entry(root)
path1.grid(row=0,column=1,padx=10,pady=5)
folder_name =[]
index =1
name = []
Button(root,text="获取表",command=get).grid(row=3,column=0,sticky=W,padx=10,pady=5)
root.mainloop()