我如何在Python中获得给定目录中的所有文件(和目录)的列表?


当前回答

我知道这是一个老问题。如果你在linux机器上,这是我遇到的一种简洁的方法。

import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))

其他回答

我知道这是一个老问题。如果你在linux机器上,这是我遇到的一种简洁的方法。

import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))

对于Python 2

#!/bin/python2

import os

def scan_dir(path):
    print map(os.path.abspath, os.listdir(pwd))

对于Python 3

对于filter和map,你需要用list()来包装它们

#!/bin/python3

import os

def scan_dir(path):
    print(list(map(os.path.abspath, os.listdir(pwd))))

现在的建议是用生成器表达式或列表推导式替换map和filter的使用:

#!/bin/python

import os

def scan_dir(path):
    print([os.path.abspath(f) for f in os.listdir(path)])

你可以使用

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

对于当前工作目录中的文件,无需指定路径

Python 2.7:

import os
os.listdir('.')

Python 3. x:

import os
os.listdir()

供参考添加扩展或ext文件的过滤器 进口操作系统

path = '.'
for dirname, dirnames, filenames in os.walk(path):
    # print path to all filenames with extension py.
    for filename in filenames:
        fname_path = os.path.join(dirname, filename)
        fext = os.path.splitext(fname_path)[1]
        if fext == '.py':
            print fname_path
        else:
            continue