用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小游戏之300行代码实现俄罗斯方块

Python小游戏之300行代码实现俄罗斯方块

前言 本文代码基于 python3.6 和 pygame1.9.4。 俄罗斯方块是儿时最经典的游戏之一,刚开始接触 pygame 的时候就想写一个俄罗斯方块。但是想到旋转,停靠,消除等操...

高质量Python代码编写的5个优化技巧

如今我使用 Python 已经很长时间了,但当我回顾之前写的一些代码时,有时候会感到很沮丧。例如,最早使用 Python 时,我写了一个名为 Sudoku 的游戏(GitHub地址:ht...

使用Python向C语言的链接库传递数组、结构体、指针类型的数据

使用python向C语言的链接库传递数组、结构体、指针类型的数据 由于最近的项目频繁使用python调用同事的C语言代码,在调用过程中踩了很多坑,一点一点写出来供大家参考,我们仍然是使用...

Python时间和字符串转换操作实例分析

本文实例讲述了Python时间和字符串转换操作。分享给大家供大家参考,具体如下: 例子: #!/usr/bin/python # -*- coding: UTF-8 -*- impo...

pytorch 数据处理:定义自己的数据集合实例

数据处理 版本1 #数据处理 import os import torch from torch.utils import data from PIL import Image im...