我如何在Python中获得给定目录中的所有文件(和目录)的列表?
当前回答
你可以使用
os.listdir(path)
参考和更多的操作系统函数看这里:
Python 2文档:https://docs.python.org/2/library/os.html#os.listdir Python 3文档:https://docs.python.org/3/library/os.html#os.listdir
其他回答
下面是我经常使用的一个辅助函数:
import os
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
你可以使用
os.listdir(path)
参考和更多的操作系统函数看这里:
Python 2文档:https://docs.python.org/2/library/os.html#os.listdir Python 3文档:https://docs.python.org/3/library/os.html#os.listdir
我写了一个很长的版本,包含了我可能需要的所有选项: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:])
这是一种遍历目录树中每个文件和目录的方法:
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')
递归实现
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)
推荐文章
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何制作好的可复制的熊猫例子
- 移动一个文件到服务器上的另一个文件夹
- 2个数字表的余弦相似度
- 如何从熊猫的两列形成元组列
- 如何读一个文本文件到一个列表或数组与Python
- Django可选url参数
- 在matplotlib上为散点图中的每个系列设置不同的颜色
- 如何加载一个tsv文件到熊猫数据框架?
- 从csv文件创建字典?
- 如何在Python中将十六进制字符串转换为字节?
- set()是如何实现的?
- 如何使Python脚本在Linux中像服务或守护进程一样运行
- 返回大列表中每n项的python方式
- 如何使用Python中的DLL文件?