【问题标题】:Python print Filename and Extention from directory and sub directoriesPython从目录和子目录中打印文件名和扩展名
【发布时间】:2014-12-06 19:08:18
【问题描述】:

您好,我正在尝试编写一个 python 脚本,该脚本可以查看目录和子目录并提取文件名和扩展名并将它们列出在文件中。感谢您的时间。 示例输出需要:

Artist
 Album name
  song.mp3
  song.wav
  song.aiff

文件存储为艺术家、专辑{可能很多}、歌曲{每张专辑}

我目前正在尝试以以下方式开始:

import os

for dirname, dirnames, filenames in os.walk('.'):

    for subdirname in dirnames:
        print os.path.join(dirname, subdirname)


    for filename in filenames:
        print os.path.join(dirname, filename)

【问题讨论】:

  • 先打开一个文件,边写边写

标签: python file printing directory filenames


【解决方案1】:

您可以通过计算基目录中的路径分隔符来跟踪您在树上走了多远。

import os

def scan_this(path):
    path = os.path.abspath(path)
    sep_count = path.count(os.path.sep) + 1

    for root, dirnames, filenames in os.walk(path):
        nest_count = root.count(os.path.sep) - sep_count
        if nest_count <= 1:
            print '%s%s' % ('  ' * nest_count, os.path.basename(root))
            if nest_count == 1:
                for f in filenames:
                    print '%s%s' % ('  ' * (nest_count + 1), f)

scan_this('.')

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2017-05-09
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多