仅列出目录中的文件?

tkb*_*kbx 33 python

有没有办法用Python列出目录中的文件(而不是目录)?我知道我可以使用os.listdir和循环的os.path.isfile()s,但如果有更简单的东西(如函数os.path.listfilesindir或其他东西),它可能会更好.

Gar*_*tty 43

这是一个简单的生成器表达式:

files = (file for file in os.listdir(path) 
         if os.path.isfile(os.path.join(path, file)))
for file in files: # You could shorten this to one line, but it runs on a bit.
    ...
Run Code Online (Sandbox Code Playgroud)

或者你可以做一个发电机功能,如果它更适合你:

def files(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            yield file
Run Code Online (Sandbox Code Playgroud)

那简单地说:

for file in files(path):
    ...
Run Code Online (Sandbox Code Playgroud)


Nei*_*eil 7

对于处理当前目录中的文件的特殊情况,您可以将其作为简单的单行列表理解:

[f for f in os.listdir(os.curdir) if os.path.isfile(f)]
Run Code Online (Sandbox Code Playgroud)

否则,在更一般的情况下,必须连接目录路径和文件名:

dirpath = '~/path_to_dir_of_interest'
files = [f for f in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, f))]
Run Code Online (Sandbox Code Playgroud)


joh*_*son 6

files = next(os.walk('..'))[2]
Run Code Online (Sandbox Code Playgroud)

  • 下一步是什么?单行答案吸引了我的注意力,但我无法理解。 (2认同)

Noa*_*nos 5

在 Windows 中使用 pathlib 如下:

files = (x for x in Path("your_path") if x.is_file())

产生错误:

类型错误:“WindowsPath”对象不可迭代

你应该使用Path.iterdir()

filePath = Path("your_path")
if filePath.is_dir():
    files = list(x for x in filePath.iterdir() if x.is_file())
Run Code Online (Sandbox Code Playgroud)


aca*_*uci 5

从 Python 3.6 开始,您可以使用带有递归选项“**”的 glob。请注意, glob 将为您提供所有文件和目录,因此您只能保留文件和目录

files = glob.glob(join(in_path, "**/*"), recursive=True)
files = [f for f in files if os.path.isfile(f)]
Run Code Online (Sandbox Code Playgroud)