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

yipeiwu_com5年前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)

相关文章

PyTorch使用cpu加载模型运算方式

没gpu没cuda支持的时候加载模型到cpu上计算 将 model = torch.load(path, map_location=lambda storage, loc: stor...

python读取并定位excel数据坐标系详解

python读取并定位excel数据坐标系详解

测试数据:坐标数据:testExcelData.xlsx 使用python读取excel文件需要安装xlrd库: xlrd下载后的压缩文件:xlrd-1.2.0.tar.gz 解压后再...

django的ORM模型的实现原理

ORM模型介绍 随着项目越来越大,采用写原生SQL的方式在代码中会出现大量的SQL语句,那么问题就出现了: SQL语句重复利用率不高,越复杂的SQL语句条件越多,代码越长。会出现...

pycharm 在windows上编辑代码用linux执行配置的方法

pycharm 在windows上编辑代码用linux执行配置的方法

如下所示: 如上图所示点击右上角 ‘configure python interpreter' 弹窗如上图所示,选择项目, ‘project interpreter'  对应...

fastcgi文件读取漏洞之python扫描脚本

fastcgi文件读取漏洞之python扫描脚本

PHP FastCGI的远程利用 说到FastCGI,大家都知道这是目前最常见的webserver动态脚本执行模型之一。目前基本所有web脚本都基本支持这种模式,甚至有的类型脚本这是唯一...