2

I saw this How to count the number of files in a directory using Python

and have this:

import os, os.path

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

but it always returns 0. How would i modify this to return the count of files?

thx

Community
  • 1
  • 1
timpone
  • 19,235
  • 36
  • 121
  • 211

1 Answers1

8

At the moment, you're calling os.path.isfile("somefile.ext"). You need to call 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))
])

Or more concisely:

print sum(
    os.path.isfile(os.path.join(homedir, name)) for name in os.listdir(homedir)
)
Eric
  • 95,302
  • 53
  • 242
  • 374
  • Maybe your rather 'expanded' layout was the reason (I didn't downvote) – Jakob Bowyer Jun 07 '12 at 14:02
  • I expanded so that it fits the code box without scrollbars. Besides, I got the downvote before that. – Eric Jun 07 '12 at 14:03
  • @jamylak: Not sure that was an improvement. Is there any official document on how to wrap list comprehensions? – Eric Jun 07 '12 at 14:06
  • http://stackoverflow.com/questions/5809059/line-continuation-for-list-comprehensions-or-generator-expressions-in-python This post is what I based it off. – jamylak Jun 07 '12 at 14:07
  • Gone for a compromise. I'm more of a wrap-and-indent than indent-by-column person. – Eric Jun 07 '12 at 14:09
  • @JoeFish: no, that's intentionally a generator expression rather than a list comprehension – Eric Jun 07 '12 at 14:13
  • (Note that it's redundant to import `os.path` explicitly.) – Sven Marnach Jun 07 '12 at 14:14
  • +1 for the version using `sum`. It is slightly non-obvious to write, but makes good sense to read. – lvc Jun 07 '12 at 14:24