当前位置:首页>python>【别再手动整理文件夹了!Python一键扫描文件夹结构,自动生成目录树并导出Excel,让你的文件管理效率飙升10倍!】

【别再手动整理文件夹了!Python一键扫描文件夹结构,自动生成目录树并导出Excel,让你的文件管理效率飙升10倍!】

  • 2026-09-02 19:26:00
【别再手动整理文件夹了!Python一键扫描文件夹结构,自动生成目录树并导出Excel,让你的文件管理效率飙升10倍!】

“带你横跨办公自动化的数据江海”

@摸鱼

闻道有先后,术业有专攻。

各位大佬好!

~我依旧是你们的老朋友摸鱼~

♥ 1

在职场摸爬滚打的这十多年里,我用Python悄悄干了不少“正事”——不知不觉攒下了一整套办公自动化的实用项目技巧。去年10月初创立了公众号 「码海听潮」 ,初衷很简单:把重复的劳动交给代码,把摸鱼的时间留给生活。

目前已经吭哧吭哧更新了近90篇原创文章,每一篇都是实操干货,不讲虚的,只聊怎么用代码真正解放双手,帮大家早点下班、准点摸鱼

♥ 2

♥ 3

好叻,多了不说,少了不唠,咱直接上干货。

办公需求场景

从崩溃到优雅的进化

有一个神秘的名为‘存档’的根文件夹,里面有一个名为‘四阶文件’的子文件夹、子文件夹下有多个递归的孙文件夹和文件,现在的需求是从这个根文件出发,把根文件夹下的递归的所有的文件夹和文件按层级来分形成目录树的结构,并且保存为excel文件目录表。要是这种类似的需求你的Big Boss安排你去完成,请问阁下该如何应对?

需求的根文件夹列表如下图:

需求的子文件夹列表如下图:

办公痛点分析

01

痛点一:目录结构复杂,手工录入极易出错

    • 当文件夹层级深(如超过5层)、子文件夹数量多(成百上千个)、文件与文件夹混杂时,手动在Excel中逐级缩进或填写层级关系,极易出现错行、漏项、层级错位。

    02

    痛点二:重复性劳动耗时巨大

      • 每次右键查看属性、复制路径、在Excel中手动整理,面对频繁变动的文件结构,维护成本极高。

      由此可见若下载成百上千个文件夹目录话整个操作流程繁琐且耗时,高频次的鼠标点击和键盘输入使操作者手指疲劳,堪称"键盘敲冒烟"式的体力劳动,加上人工疲劳操作极易导致遗漏文件夹。于是乎这时候,按以往的 “解题套路”,Python 的专属 BGM 该响起来了 ——go~ go~ go~,救苦救难的大救星这不就来了!!

      @摸鱼

      问题拆解思路

      1.遍历需求的根目录文件夹→

      2.对遍历所有子目录和文件,记录每个文件/文件夹的层级关系(第1层、第2层...)→

      3.把获取的相关数据写入excel表格中并保存。

      下面,我就用python代码让各位大佬见识一下,什么叫"传统文化遇上赛博效率"(仅展示部分代码,非完整代码,需完整代码看文章末尾说明~)

      import sysfrom PyQt6.QtWidgets import (    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,    QPushButton, QLineEdit, QLabel, QFileDialog, QTableWidget,    QTableWidgetItem, QProgressBar, QGroupBox,    QSplitter, QHeaderView)from PyQt6.QtCore import Qt, QSizefrom PyQt6.QtGui import QFontclass MainWindow(QMainWindow):    """主窗口"""    def __init__(self):        super().__init__()        self.setWindowTitle("文件目录树生成器(欢迎关注微信公众号:码海听潮)")        self.setMinimumSize(750, 650)        # 设置窗口样式        self.setStyleSheet("""            QMainWindow {                background-color: #f5f5f5;            }            QGroupBox {                font-weight: bold;                border: 2px solid #cccccc;                border-radius: 8px;                margin-top: 10px;                padding-top: 10px;                background-color: white;            }            QGroupBox::title {                subcontrol-origin: margin;                left: 10px;                padding: 0 5px 0 5px;            }            QPushButton {                background-color: #4CAF50;                border: none;                color: white;                padding: 8px 16px;                border-radius: 4px;                font-weight: bold;            }            QPushButton:hover {                background-color: #45a049;            }            QPushButton:pressed {                background-color: #3d8b40;            }            QPushButton:disabled {                background-color: #cccccc;            }            QLineEdit {                padding: 6px;                border: 1px solid #cccccc;                border-radius: 4px;                font-size: 12px;            }            QLineEdit:focus {                border-color: #4CAF50;            }            QTableWidget {                border: 1px solid #cccccc;                border-radius: 4px;                background-color: white;                gridline-color: #e0e0e0;            }            QTableWidget::item {                padding: 4px;            }            QHeaderView::section {                background-color: #f0f0f0;                padding: 4px;                border: 1px solid #cccccc;                font-weight: bold;            }            QProgressBar {                border: 1px solid #cccccc;                border-radius: 4px;                text-align: center;                background-color: white;            }            QProgressBar::chunk {                background-color: #4CAF50;                border-radius: 3px;            }        """)        # 创建中心部件        central_widget = QWidget()        self.setCentralWidget(central_widget)        # 主布局        main_layout = QVBoxLayout(central_widget)        main_layout.setSpacing(10)        main_layout.setContentsMargins(15, 15, 15, 15)        # 创建分割器        splitter = QSplitter(Qt.Orientation.Vertical)        # 上半部分:控制区域        control_widget = QWidget()        control_layout = QVBoxLayout(control_widget)        control_layout.setSpacing(10)        # 路径选择组        path_group = QGroupBox("目录选择")        path_layout = QVBoxLayout(path_group)        # 路径输入行        path_input_layout = QHBoxLayout()        self.path_input = QLineEdit()        self.path_input.setPlaceholderText("请输入目录路径或点击浏览选择...")        self.browse_btn = QPushButton("浏览...")        path_input_layout.addWidget(self.path_input)        path_input_layout.addWidget(self.browse_btn)        # 使用当前目录按钮        self.use_current_btn = QPushButton("使用当前目录")        path_layout.addLayout(path_input_layout)        path_layout.addWidget(self.use_current_btn)        control_layout.addWidget(path_group)        # 操作按钮组        button_group = QGroupBox("操作")        button_layout = QHBoxLayout(button_group)        self.generate_btn = QPushButton("生成目录树")        self.generate_btn.setMinimumHeight(40)        self.generate_btn.setStyleSheet("font-size: 14px;")        self.export_btn = QPushButton("导出Excel")        self.export_btn.setMinimumHeight(40)        self.export_btn.setStyleSheet("font-size: 14px; background-color: #2196F3;")        self.export_btn.setEnabled(False)        # 创建水平布局用于居中显示按钮        button_widget_layout = QHBoxLayout()        button_widget_layout.addStretch()        button_widget_layout.addWidget(self.generate_btn)        button_widget_layout.addWidget(self.export_btn)        button_widget_layout.addStretch()        button_widget_layout.setSpacing(20)        button_layout.addLayout(button_widget_layout)        control_layout.addWidget(button_group)        # 进度显示组        progress_group = QGroupBox("进度")        progress_layout = QVBoxLayout(progress_group)        self.progress_bar = QProgressBar()        self.progress_bar.setVisible(False)        self.status_label = QLabel("就绪")        self.status_label.setStyleSheet("color: #666; padding: 5px;")        progress_layout.addWidget(self.progress_bar)        progress_layout.addWidget(self.status_label)        control_layout.addWidget(progress_group)        splitter.addWidget(control_widget)        # 下半部分:预览区域        preview_group = QGroupBox("预览")        preview_layout = QVBoxLayout(preview_group)        # 添加预览信息标签        preview_info_layout = QHBoxLayout()        self.preview_count_label = QLabel("共0条记录")        self.preview_count_label.setStyleSheet("color: #666; padding: 5px;")        preview_info_layout.addWidget(self.preview_count_label)        preview_info_layout.addStretch()        self.preview_table = QTableWidget()        self.preview_table.setAlternatingRowColors(True)        self.preview_table.horizontalHeader().setStretchLastSection(True)        preview_layout.addLayout(preview_info_layout)        preview_layout.addWidget(self.preview_table)        splitter.addWidget(preview_group)        # 设置分割器比例        splitter.setStretchFactor(0, 1)        splitter.setStretchFactor(1, 2)        main_layout.addWidget(splitter)        # 状态栏        self.statusBar().showMessage("就绪")def main():    app = QApplication(sys.argv)    # 设置应用程序字体    font = QFont("微软雅黑", 9)    app.setFont(font)    window = MainWindow()    window.show()    sys.exit(app.exec())if __name__ == "__main__":    main()

      最终将根文件夹下的目录树结构提取出来并保存为excel表,实现了之前既定的需求....

      通过上面Python自动化脚本,仅用几分钟的时间就完成原需手动操作数小时甚至数天的工作任务。从最初准备手动人工机械操作的麻木到用python实现高效自动化的畅快,工作效率获得指数级提升,终于实现了不加班熬夜的自由!

      大佬们也可以举一反三,参照上面的代码思路根据自己工作中的实际情况来具体问题具体分析,实现自己定制化的需求。

      结语

      当Python遇见办公,牛马打工人终于笑出了猪叫声

      【职场人必看】每天早上一睁眼,想到又要面对:

      1.📊 堆积如山的Excel表格

      2.📑 机械重复的复制粘贴

      3.✍️ 永远改不完的各类文档

      4.诸如此类的更多........

      是不是连Ctrl+Alt+Delete的心都有了?

      别慌!别急,摸鱼这位“职场外挂”已经带着Python代码来拯救你了!

      友情提示:考虑到没有python环境的朋友需要打包好的成品exe,摸鱼早已贴心打包好,本篇文章代码打包的exe截图如下:

      另外,《码海听潮》公众号所有文章码和exe程序已打包好上传绿联nas私有云,有需要的大佬扫一扫上面博主的个人微信二维码,需要的大佬需支付9.9元永久拥有公众号资源(写原创干货费时费力,属实不易),邀请您进入社区群获取下载链接!!,群内提供python办公自动化交流问题,解决问题,且码海听潮微信公众号文章发布会第一时间会更新到群里,非诚勿扰哈!

      码海听潮官方社区群如下:

      赶紧微信扫一扫下方二维码添加摸鱼君微信

      最新文章

      随机文章