大家好,我是菜鸟。
因为想将目录中的文件名导出到表格中,所以写了这个小程序,请各位大神指点。谢谢
1.遍历指定目录及子目录中的文件,将文件名输出至表格。
2.表格第1列为序号,第2列为一级目录,第3列为二级目录,第4列为文件名,第5列为文件地址。
3.点击“选择目录”,选择要遍历的目录,点击“输出到表格”,可以遍历目录及文件名到表格,并打开表格。
代码如下:
[Python] 纯文本查看 复制代码 import os
import tkinter as tk
from tkinter import filedialog
from openpyxl import Workbook
def browse_folder():
folder_selected = filedialog.askdirectory()
if folder_selected:
entry_folder.delete(0, tk.END)
entry_folder.insert(0, folder_selected)
def save_to_excel():
folder_path = entry_folder.get()
if not folder_path:
return
workbook = Workbook()
sheet = workbook.active
sheet.title = "Files"
sheet.append(["序号", "一级目录", "二级目录", "文件名", "文件地址"])
index = 1
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
directory = os.path.relpath(root, folder_path)
parts = directory.split(os.sep)
first_level = parts[0] if len(parts) > 0 else ""
second_level = parts[1] if len(parts) > 1 else ""
sheet.append([index, first_level, second_level, file, file_path])
index += 1
file_path = filedialog.asksaveasfilename(defaultextension=".xlsx", filetypes=[("Excel files", "*.xlsx")])
if file_path:
workbook.save(file_path)
open_excel(file_path)
def open_excel(file_path):
os.startfile(file_path)
# 创建主窗口
root = tk.Tk()
root.title("目录遍历到表格")
# 创建输入框和按钮
entry_folder = tk.Entry(root, width=50)
entry_folder.pack(pady=10)
button_browse = tk.Button(root, text="选择目录", command=browse_folder)
button_browse.pack(pady=5)
button_save = tk.Button(root, text="输出到表格", command=save_to_excel)
button_save.pack(pady=5)
root.mainloop()
运行截图如下:
|