想在python中获取home dir中的文件数

tim*_*one 2 python

我看到了如何使用Python计算目录中的文件数

有这个:

import os, os.path

print len([name for name in os.listdir(os.path.expanduser("~")) if os.path.isfile(name)])
Run Code Online (Sandbox Code Playgroud)

但它总是返回0.如何修改此返回文件的数量?

谢谢

Eri*_*ric 8

此刻,你正在打电话os.path.isfile("somefile.ext").你需要打电话os.path.isfile("~/somefile.ext").

import os

homedir = os.path.expanduser("~")
print len([
    name
    for name in os.listdir(homedir)
    if os.path.isfile(os.path.join(homedir, name))
])
Run Code Online (Sandbox Code Playgroud)

或者更简洁:

print sum(
    os.path.isfile(os.path.join(homedir, name)) for name in os.listdir(homedir)
)
Run Code Online (Sandbox Code Playgroud)