【问题标题】:Python: how to obtain only first filename in the directoryPython:如何仅获取目录中的第一个文件名
【发布时间】:2015-02-12 20:26:57
【问题描述】:

我有各种目录的路径。现在我想查看每个目录中第一个文件的头信息。

例如:path = "Users/SDB/case_23/scan_1"

现在在子目录scan_1 我想检查一些标题信息。为此,如何获取子目录中第一个文件的完整路径和名称(按名称)?

【问题讨论】:

  • 第一个文件是什么意思?

标签: python path filenames


【解决方案1】:

os.walk

os.walk(top, topdown=True, onerror=None, followlinks=False) 通过自上而下或自下而上遍历树,在目录树中生成文件名。对于以目录顶部为根的树中的每个目录(包括顶部本身),它会产生一个三元组(dirpath, dirnames, filenames)。 ...

示例

目录结构

$ tree -d
.
└── users
    └── sdb
        └── case_23
            └── scan_1

目录+文件结构

$ tree
.
├── a.txt
├── b.txt
├── c.txt
└── users
    ├── a.txt
    ├── b.txt
    ├── c.txt
    └── sdb
        ├── a.txt
        ├── b.txt
        ├── c.txt
        └── case_23
            ├── d.txt
            ├── e.txt
            ├── f.txt
            └── scan_1
                ├── a.txt
                ├── b.txt
                └── c.txt

python 代码

>>> import os
>>> rootdir = '/tmp/so'
>>> # print full path for first file in rootdir and for each subdir
... for topdir, dirs, files in os.walk(rootdir):
...     firstfile = sorted(files)[0]
...     print os.path.join(topdir, firstfile)
... 
/tmp/so/a.txt
/tmp/so/users/a.txt
/tmp/so/users/sdb/a.txt
/tmp/so/users/sdb/case_23/d.txt
/tmp/so/users/sdb/case_23/scan_1/a.txt

【讨论】:

  • 没有列出目录的顺序,因此使用它可能无法获取任何 第一个文件
  • @PadraicCunningham 当然,但是第一个文件是什么意思?按名称、日期、修改时间排序? ;)
  • 这就是我向 OP 提出的要求。现在我不知道这个问题意味着什么,所以投票结束。当 OP 已经在使用它时,不确定为什么需要完整路径!
  • @PadraicCunningham 同意,这就是我给出“抽象”答案的原因。
  • 感谢您的回复。对不起,我没有清楚地提到它。我正在按名称查找目录中的第一个文件。
猜你喜欢
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2015-05-04
相关资源
最近更新 更多