Python: 如何只获取目录中的第一个文件名
Python: how to obtain only first filename in the directory
我有各种目录的路径。现在我想查看每个目录中第一个文件的 header 信息。
例如:path = "Users/SDB/case_23/scan_1"
现在在子目录scan_1
中,我想查看一些header信息。为此,我怎样才能获得子目录中第一个文件的完整路径和名称(按名称)?
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)
.
...
例子
目录结构
$ 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
我有各种目录的路径。现在我想查看每个目录中第一个文件的 header 信息。
例如:path = "Users/SDB/case_23/scan_1"
现在在子目录scan_1
中,我想查看一些header信息。为此,我怎样才能获得子目录中第一个文件的完整路径和名称(按名称)?
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)
. ...
例子
目录结构
$ 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