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

yipeiwu_com6年前Python基础

有时候需要罗列下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遍历目录的4种方法实例介绍

1.os.popen运行shell列表命令 复制代码 代码如下: def traverseDirByShell(path):     for f in os...

python实现搜索文本文件内容脚本

python实现搜索文本文件内容脚本

本文介绍用python实现的搜索本地文本文件内容的小程序。从而学习Python I/O方面的知识。代码如下: import os #根据文件扩展名判断文件类型 def endWit...

用python实现将数组元素按从小到大的顺序排列方法

如下所示: def findSmallest(arr): smallest = arr[0]#将第一个元素的值作为最小值赋给smallest smallest_index = 0...

使用python删除nginx缓存文件示例(python文件操作)

调用时输入参数如:  www.jb51.net/表示删除www.jb51.net首页的缓存, www.jb51.net/test.php就表示删除/test.php的缓存复制代...

pygame游戏之旅 载入小车图片、更新窗口

pygame游戏之旅 载入小车图片、更新窗口

本文为大家分享了pygame游戏之旅的第3篇,供大家参考,具体内容如下 载入car图片(我自己画的),需要用到pygame.image模块,定义carImg用于接收载入的图片 car...