Python: 获取目录中首个文件名

2024-06-03 00:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 文件path路径目录名称信息scanusers
1条回答
网友
1楼 · 发布于 2024-06-03 00:29:32

os.walk

os.walk(top, topdown=True, onerror=None, followlinks=False) Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). ...

示例

dirs结构

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

dirs+文件结构

^{pr2}$

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

相关问题 更多 >