用Python编写生成树状结构的文件目录的脚本的教程

作者:goldensun 时间:2022-12-26 09:54:52 

有时候需要罗列下U盘等移动设备或一个程序下面的目录结构的需求。基于这样的需求个人整理了一个使用Python的小工具,期望对有这方面需求的朋友有所帮助。以下为具体代码:

如果你所有要求的文件目录不需要完整的文件路径的话,直接更换下面的注释代码即可~
 


# -*- coding:utf-8 -*-
import os
def list_files(startPath):
 fileSave = open('list.txt','w')
 for root, dirs, files in os.walk(startPath):
   level = root.replace(startPath, '').count(os.sep)
   indent = ' ' * 1 * level
   #fileSave.write('{}{}/'.format(indent, os.path.basename(root)) + '\n')
   fileSave.write('{}{}\\'.format(indent, os.path.abspath(root)) + '\n')
   subIndent = ' ' * 1 * (level + 1)
   for f in files:
     #fileSave.write('{}{}'.format(subIndent, f) + '\n')
     fileSave.write('{}{}{}'.format(subIndent, os.path.abspath(root), f) + '\n')
 fileSave.close()

dir = raw_input('please input the path:')
list_files(dir)
标签:Python
0
投稿

猜你喜欢

  • Python+Selenium+Pytesseract实现图片验证码识别

    2023-08-17 11:44:01
  • python 模拟网站登录——滑块验证码的识别

    2023-04-17 16:16:29
  • 微信跳一跳辅助python代码实现

    2023-03-26 15:25:50
  • Git的基本操作流程及工作区版本库暂存区的关系

    2022-03-10 04:52:42
  • 使用Python编写一个模仿CPU工作的程序

    2021-04-28 05:28:25
  • 将pytorch的网络等转移到cuda

    2023-08-10 08:33:46
  • Python 通过微信控制实现app定位发送到个人服务器再转发微信服务器接收位置信息

    2023-02-15 16:49:10
  • MYSQL教程:查询优化之有效加载数据

    2009-02-27 15:45:00
  • Python中使用Flask、MongoDB搭建简易图片服务器

    2021-12-09 19:57:16
  • Python-OpenCV深度学习入门示例详解

    2022-07-24 02:44:24
  • v语言初体验小结

    2022-09-22 01:02:51
  • $.browser.msie 为空或不是对象问题的多种解决方法

    2024-05-11 09:33:55
  • Python守护进程(daemon)代码实例

    2021-10-21 21:15:54
  • 在Python下利用OpenCV来旋转图像的教程

    2022-12-18 22:53:46
  • 如何将计数器的值赋给一个变量?

    2009-12-03 20:02:00
  • 如何提示用户打开Cookie?

    2010-06-07 20:53:00
  • Python中的random函数实例详解

    2021-01-09 13:01:49
  • vue中的input框点击后不聚焦问题

    2024-05-02 16:33:12
  • ASP:一个网站空间多个域名访问

    2008-11-21 17:03:00
  • 18个帮你简化代码的Python技巧分享

    2021-08-12 02:41:12
  • asp之家 网络编程 m.aspxhome.com