Mat*_*att 559 python directory file subdirectory directory-tree
如何获取Python中给定目录中所有文件(和目录)的列表?
Jer*_*rub 610
这是遍历目录树中每个文件和目录的方法:
import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
Run Code Online (Sandbox Code Playgroud)
rsl*_*ite 530
您可以使用
os.listdir(path)
Run Code Online (Sandbox Code Playgroud)
有关参考和更多os函数,请在此处查看:
gil*_*tay 107
这是我经常使用的辅助函数:
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
Run Code Online (Sandbox Code Playgroud)
cur*_*isk 82
import os
for filename in os.listdir("C:\\temp"):
print filename
Run Code Online (Sandbox Code Playgroud)
ken*_*nny 13
如果你需要通配能力,那么也有一个模块.例如:
import glob
glob.glob('./[0-9].*')
Run Code Online (Sandbox Code Playgroud)
将返回如下内容:
['./1.gif', './2.txt']
Run Code Online (Sandbox Code Playgroud)
请参阅此处的文档.
pax*_*blo 10
试试这个:
import os
for top, dirs, files in os.walk('./'):
for nm in files:
print os.path.join(top, nm)
Run Code Online (Sandbox Code Playgroud)
对于当前工作目录中的文件而不指定路径
Python 2.7:
import os
os.listdir(os.getcwd())
Run Code Online (Sandbox Code Playgroud)
Python 3.x:
import os
os.listdir()
Run Code Online (Sandbox Code Playgroud)
感谢Stam Kaly对python 3.x的评论
虽然os.listdir()生成文件和目录名称列表很好,但一旦获得这些名称,您通常会想要执行更多操作 - 在 Python3 中,pathlib使其他杂务变得简单。让我们来看看,看看你是否和我一样喜欢它。
要列出 dir 内容,请构造一个 Path 对象并获取迭代器:
In [16]: Path('/etc').iterdir()
Out[16]: <generator object Path.iterdir at 0x110853fc0>
Run Code Online (Sandbox Code Playgroud)
如果我们只想要一个事物名称列表:
In [17]: [x.name for x in Path('/etc').iterdir()]
Out[17]:
['emond.d',
'ntp-restrict.conf',
'periodic',
Run Code Online (Sandbox Code Playgroud)
如果你只想要目录:
In [18]: [x.name for x in Path('/etc').iterdir() if x.is_dir()]
Out[18]:
['emond.d',
'periodic',
'mach_init.d',
Run Code Online (Sandbox Code Playgroud)
如果您想要该树中所有conf文件的名称:
In [20]: [x.name for x in Path('/etc').glob('**/*.conf')]
Out[20]:
['ntp-restrict.conf',
'dnsextd.conf',
'syslog.conf',
Run Code Online (Sandbox Code Playgroud)
如果您想要树中 >= 1K 的 conf 文件列表:
In [23]: [x.name for x in Path('/etc').glob('**/*.conf') if x.stat().st_size > 1024]
Out[23]:
['dnsextd.conf',
'pf.conf',
'autofs.conf',
Run Code Online (Sandbox Code Playgroud)
解析相对路径变得很容易:
In [32]: Path('../Operational Metrics.md').resolve()
Out[32]: PosixPath('/Users/starver/code/xxxx/Operational Metrics.md')
Run Code Online (Sandbox Code Playgroud)
使用路径导航非常清晰(尽管出乎意料):
In [10]: p = Path('.')
In [11]: core = p / 'web' / 'core'
In [13]: [x for x in core.iterdir() if x.is_file()]
Out[13]:
[PosixPath('web/core/metrics.py'),
PosixPath('web/core/services.py'),
PosixPath('web/core/querysets.py'),
Run Code Online (Sandbox Code Playgroud)
递归实现
import os
def scan_dir(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path):
print path
else:
scan_dir(path)
Run Code Online (Sandbox Code Playgroud)
这是另一种选择。
os.scandir(path='.')
Run Code Online (Sandbox Code Playgroud)
它返回与路径给定的目录中的条目(以及文件属性信息)相对应的 os.DirEntry 对象的迭代器。
例子:
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.'):
print(entry.name)
Run Code Online (Sandbox Code Playgroud)
使用 scandir() 而不是 listdir() 可以显着提高还需要文件类型或文件属性信息的代码的性能,因为如果操作系统在扫描目录时提供此信息,则 os.DirEntry 对象会公开此信息。所有 os.DirEntry 方法都可以执行系统调用,但 is_dir() 和 is_file() 通常只需要符号链接的系统调用;os.DirEntry.stat() 在 Unix 上总是需要系统调用,但在 Windows 上只需要符号链接。