我如何在Python中获得给定目录中的所有文件(和目录)的列表?
当前回答
只递归列出文件的漂亮的一行代码。我在setup.py package_data指令中使用了这个:
import os
[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]
我知道这不是问题的答案,但可能会派上用场
其他回答
我知道这是一个老问题。如果你在linux机器上,这是我遇到的一种简洁的方法。
import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))
递归实现
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)
虽然os.listdir()用于生成文件和目录名称的列表很好,但一旦有了这些名称,通常您还想做更多的事情——在Python3中,pathlib使这些其他杂事变得简单。让我们看一看,看看你是否和我一样喜欢它。
要列出目录内容,构造一个Path对象并获取迭代器:
In [16]: Path('/etc').iterdir()
Out[16]: <generator object Path.iterdir at 0x110853fc0>
如果我们只想要一个事物名称的列表
In [17]: [x.name for x in Path('/etc').iterdir()]
Out[17]:
['emond.d',
'ntp-restrict.conf',
'periodic',
如果你只想要dirs:
In [18]: [x.name for x in Path('/etc').iterdir() if x.is_dir()]
Out[18]:
['emond.d',
'periodic',
'mach_init.d',
如果你想要该树中所有conf文件的名称:
In [20]: [x.name for x in Path('/etc').glob('**/*.conf')]
Out[20]:
['ntp-restrict.conf',
'dnsextd.conf',
'syslog.conf',
如果你想在树>= 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',
解析相对路径变得简单:
In [32]: Path('../Operational Metrics.md').resolve()
Out[32]: PosixPath('/Users/starver/code/xxxx/Operational Metrics.md')
使用路径导航非常清楚(尽管出乎意料):
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'),
下面是一行python版本:
import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]
这段代码列出给定目录名中所有文件和目录的完整路径。
我写了一个很长的版本,包含了我可能需要的所有选项:http://sam.nipl.net/code/python/find.py
我想它也适合这里:
#!/usr/bin/env python
import os
import sys
def ls(dir, hidden=False, relative=True):
nodes = []
for nm in os.listdir(dir):
if not hidden and nm.startswith('.'):
continue
if not relative:
nm = os.path.join(dir, nm)
nodes.append(nm)
nodes.sort()
return nodes
def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
root = os.path.join(root, '') # add slash if not there
for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
if relative:
parent = parent[len(root):]
if dirs and parent:
yield os.path.join(parent, '')
if not hidden:
lfiles = [nm for nm in lfiles if not nm.startswith('.')]
ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place
if files:
lfiles.sort()
for nm in lfiles:
nm = os.path.join(parent, nm)
yield nm
def test(root):
print "* directory listing, with hidden files:"
print ls(root, hidden=True)
print
print "* recursive listing, with dirs, but no hidden files:"
for f in find(root, dirs=True):
print f
print
if __name__ == "__main__":
test(*sys.argv[1:])
推荐文章
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何制作好的可复制的熊猫例子
- 移动一个文件到服务器上的另一个文件夹
- 2个数字表的余弦相似度
- 如何从熊猫的两列形成元组列
- 如何读一个文本文件到一个列表或数组与Python
- Django可选url参数
- 在matplotlib上为散点图中的每个系列设置不同的颜色
- 如何加载一个tsv文件到熊猫数据框架?
- 从csv文件创建字典?
- 如何在Python中将十六进制字符串转换为字节?
- set()是如何实现的?
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 返回大列表中每n项的python方式
- 如何使用Python中的DLL文件?