用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)

相关文章

python加载自定义词典实例

如下所示: #加载词典 def load_dict_from_file(filepath): _dict = {} try: with io.open(filepat...

python OpenCV学习笔记直方图反向投影的实现

python OpenCV学习笔记直方图反向投影的实现

本文介绍了python OpenCV学习笔记直方图反向投影的实现,分享给大家,具体如下: 官方文档 – https://docs.opencv.org/3.4.0/dc/df6/tuto...

Python操作MySQL数据库的三种方法总结

Python操作MySQL数据库的三种方法总结

1. MySQLdb 的使用 (1) 什么是MySQLdb? MySQLdb 是用于 Python 连接 MySQL 数据库的接口,它实现了 Python 数据库 API 规范 V2.0...

python读写二进制文件的方法

本文实例讲述了python读写二进制文件的方法。分享给大家供大家参考。具体如下: 初学python,现在要读一个二进制文件,查找doc只发现 file提供了一个read和write函数,...

Python使用文件锁实现进程间同步功能【基于fcntl模块】

本文实例讲述了Python使用文件锁实现进程间同步功能。分享给大家供大家参考,具体如下: 简介 在实际应用中,会出现这种应用场景:希望shell下执行的脚本对某些竞争资源提供保护,避免出...