[Python] 读取所有目录和文件

2019-11-08  本文已影响0人  棘刺
# -*- coding: utf-8 -*-

import os

# 目录遍历方法
def checkDir(path, folder, count):
    # 检查是否是第一级目录,不是的话在目录命名前加斜杠\
    if folder != "":
        folder = folder + '\\'
    # 遍历path目录
    for i, j, k in os.walk(path):
        # 如果该目录下存在非目录文件,则先写入
        if k != []:
            for kk in k:
                print("├{} {}{}".format("─" * count, folder, kk))
                w_file.write("├{} {}{}\n".format("─" * count, folder, kk))
        # 如果存在子目录,则进入下一个目录遍历方法
        if j != []:
            for jj in j:
                print("├{} {}{}".format("─" * count, folder, jj))
                w_file.write("├{} {}{}\n".format("─" * count, folder, jj))
                checkDir("{}\\{}".format(i, jj), jj, count + 1)
        break


if __name__ == '__main__':
    # 新建txt,以上一级文件夹名命名
    w_file = open('{}.txt'.format(os.getcwd().split('\\')[-1]), 'w', encoding='utf-8')
    # 获取当前路径
    filePath = os.getcwd()
    # 写入当前文件路径
    w_file.write("{}".format(filePath))
    print("{}".format(filePath))
    # ”─“计数器
    count = 0
    # 调用目录遍历方法
    checkDir(filePath, "", 0)
    # 写入文件结束标志符
    w_file.write("└ #")
    print("└ #")
    # 关闭文件
    w_file.close()

上一篇下一篇

猜你喜欢

热点阅读