gpt4 book ai didi

python - 想在 python 中获取主目录中的文件数

转载 作者:行者123 更新时间:2023-11-28 20:26:38 24 4
gpt4 key购买 nike

我看到了这个How to count the number of files in a directory using Python

并拥有这个:

import os, os.path

print len([name for name in os.listdir(os.path.expanduser("~")) if os.path.isfile(name)])

但它总是返回 0。我该如何修改它以返回文件数?

谢谢

最佳答案

此刻,您正在调用 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))
])

或者更简洁:

print sum(
os.path.isfile(os.path.join(homedir, name)) for name in os.listdir(homedir)
)

关于python - 想在 python 中获取主目录中的文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10933234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com