473,545 Members | 1,744 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

count files in a directory

rbt
I assume that there's a better way than this to count the files in a
directory recursively. Is there???

def count_em(valid_ path):
x = 0
for root, dirs, files in os.walk(valid_p ath):
for f in files:
x = x+1
print "There are", x, "files in this directory."
return x

rbt
Jul 19 '05 #1
10 22889
On Friday 20 May 2005 07:12 pm, rbt wrote:
I assume that there's a better way than this to count the files in a
directory recursively. Is there???

def count_em(valid_ path):
x = 0
for root, dirs, files in os.walk(valid_p ath):
for f in files:
x = x+1
print "There are", x, "files in this directory."
return x

rbt


def count_em(valid_ path):
root, dirs, files = os.walk(valid_p ath)
return len(files)

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #2

Come to think of it

file_count = len(os.walk(val id_path)[2])

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #3
James Stroud wrote:
Come to think of it

file_count = len(os.walk(val id_path)[2])

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/


Somee possible answers are:

# files directly in path
file_count = len(os.walk(pat h)[2])

# files and dirs directly in path
file_count = len(os.listdir( path))

# files in or below path
file_count = 0
for root, dirs, files in os.walk(path):
file_count += len(files)
# files and dirs in or below path
file_count = 0
for root, dirs, files in os.walk(path):
file_count += len(files) + len(dirs)
--Scott David Daniels
Sc***********@A cm.Org
Jul 19 '05 #4
rbt
James Stroud wrote:
Come to think of it

file_count = len(os.walk(val id_path)[2])


I get this traceback:

PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] on win32.
Portions Copyright 1994-2004 Mark Hammond (mh******@skipp inet.com.au) - see
'Help/About PythonWin' for further copyright information.
Traceback (most recent call last):
File "C:\Program
Files\Python24\ Lib\site-packages\python win\pywin\frame work\scriptutil s.py", line 310,
in RunScript
exec codeObject in __main__.__dict __
File "C:\Documen ts and Settings\rbt\De sktop\newa\repl icate.py", line 57, in ?
A = count_em(X)
File "C:\Documen ts and Settings\rbt\De sktop\newa\repl icate.py", line 51, in count_em
count = len(os.walk(val id_path)[2])
TypeError: unsubscriptable object
Jul 19 '05 #5
rbt
James Stroud wrote:
def count_em(valid_ path):
root, dirs, files = os.walk(valid_p ath)
return len(files)


Here's another Tback:
Traceback (most recent call last):

File "C:\Program
Files\Python24\ Lib\site-packages\python win\pywin\frame work\scriptutil s.py", line 310,
in RunScript
exec codeObject in __main__.__dict __
File "C:\Documen ts and Settings\rbt\De sktop\newa\repl icate.py", line 62, in ?
A = count_em(X)
File "C:\Documen ts and Settings\rbt\De sktop\newa\repl icate.py", line 56, in count_em
root, dirs, files = os.walk(valid_p ath)
ValueError: need more than 2 values to unpack

Jul 19 '05 #6
Sorry, I've never used os.walk and didn't realize that it is a generator.

This will work for your purposes (and seems pretty fast compared to the
alternative):

file_count = len(os.walk(val id_path).next()[2])
The alternative is:
import os
import os.path

file_count = len([f for f in os.listdir('.') if os.path.isfile( f)])
On Friday 20 May 2005 08:08 pm, rbt wrote:
James Stroud wrote:
def count_em(valid_ path):
root, dirs, files = os.walk(valid_p ath)
return len(files)


Here's another Tback:
>>> Traceback (most recent call last):


File "C:\Program
Files\Python24\ Lib\site-packages\python win\pywin\frame work\scriptutil s.py",
line 310, in RunScript
exec codeObject in __main__.__dict __
File "C:\Documen ts and Settings\rbt\De sktop\newa\repl icate.py", line 62,
in ? A = count_em(X)
File "C:\Documen ts and Settings\rbt\De sktop\newa\repl icate.py", line 56,
in count_em root, dirs, files = os.walk(valid_p ath)
ValueError: need more than 2 values to unpack


--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 19 '05 #7
Am Samstag, 21. Mai 2005 06:25 schrieb James Stroud:
This will work for your purposes (and seems pretty fast compared to the
alternative):

file_count = len(os.walk(val id_path).next()[2])


But will only work when you're just scanning a single directory with no
subdirectories. ..!

The alternative (which will work regardless of subdirectories) is something
like the following:

heiko@heiko ~ $ python
Python 2.4 (#1, Apr 3 2005, 00:49:51)
[GCC 3.4.3-20050110 (Gentoo Linux 3.4.3.20050110-r1, ssp-3.4.3.20050110-0,
pie- on linux2
Type "help", "copyright" , "credits" or "license" for more information.
import os
path = "/home/heiko"
file_count = sum((len(f) for _, _, f in os.walk(path)))
file_count 55579


HTH!

--
--- Heiko.
see you at: http://www.stud.mh-hannover.de/~hwundram/wordpress/

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQBCjvUvf0b pgh6uVAMRAuuAAJ wOwIgb9Ir3pTZex 7dqc65FiOpd9QCf TA+x
FHMoRzqJiL6cVP9 n6NwmpkM=
=s6qV
-----END PGP SIGNATURE-----

Jul 19 '05 #8
rbt
Heiko Wundram wrote:
Am Samstag, 21. Mai 2005 06:25 schrieb James Stroud:
This will work for your purposes (and seems pretty fast compared to the
alternative ):

file_count = len(os.walk(val id_path).next()[2])

But will only work when you're just scanning a single directory with no
subdirectories. ..!

The alternative (which will work regardless of subdirectories) is something
like the following:

heiko@heiko ~ $ python
Python 2.4 (#1, Apr 3 2005, 00:49:51)
[GCC 3.4.3-20050110 (Gentoo Linux 3.4.3.20050110-r1, ssp-3.4.3.20050110-0,
pie- on linux2
Type "help", "copyright" , "credits" or "license" for more information.
import os
path = "/home/heiko"
file_coun t = sum((len(f) for _, _, f in os.walk(path)))
file_coun t


55579
HTH!


Thanks! that works great... is there any significance to the underscores that you
used? I've always used root, dirs, files when using os.walk() do the underscores make
it faster... or more efficient?
Jul 19 '05 #9
rbt
James Stroud wrote:
Sorry, I've never used os.walk and didn't realize that it is a generator.

This will work for your purposes (and seems pretty fast compared to the
alternative):

file_count = len(os.walk(val id_path).next()[2])


Thanks James... this works *really* well for times when I only need to count files in
the current directory (no recursion). I think others will find it useful as well.
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2645
by: Gary Feldman | last post by:
Since I prefer to keep all my installed programs in one place, I went ahead and installed Python in Program Files/Python. The command line shell seems to work just fine, and I'm able to import things like urllib and its dependencies. However, I can't get Idle to startup. When I try running it manually (i.e. python ...idle.py), I get...
2
1970
by: Bill | last post by:
I have looked up and down for a solution to this problem without any luck. I sell stuff on ebay. ebay will allow me to place javascript in my listings which I use to show a series of thumbnails of my item. In my script I have a variable that defines the number of pictures of that item. What I would like to do is have the script determine the...
1
13402
by: Sue | last post by:
How can I count the number of files in a folder? Thanks for all help!! Sue
0
1137
by: JuLiE Dxer | last post by:
Is there a way to programmatically determine if MCE isn't saving the recorded tv video files in the default directory? It'd be nice to know if the saved files aren't in the C:\Documents and Settings\All Users\Documents\Recorded TV\ directory.
0
2087
by: Don | last post by:
I intermittently get a runtime Compilation Error that says 'The compiler failed with error code 2000'. It appears that a DLL cannot be found in the 'temporary asp.net files' directory. The Detailed Compiler Output is at the bottom of this post. This is a custom dll named UtilitiesINGR.dll that I put in the GAC. I added a machine.config...
3
6395
by: glub glub | last post by:
i'm trying to make a program that works as Replace works in MS Word but this is for use with files, not a text document. FolderBrowserDialog1.ShowDialog() txtPath.Text = FolderBrowserDialog1.SelectedPath above are the 2 lines of code i have so far, i would like to display/add the files to a list view and i feel that i would have to count...
1
1484
by: Shawn Mehaffie | last post by:
I have an application I want to be able to: 1) Store user specifc settings in ther "My Documents". 2) Store some information in "All Users" document directory. 3) I also want to be able to access program files that are installed in the "Program Files" directory. How can I get these locations from within a VB application.
4
30280
by: laredotornado | last post by:
Hello, Using PHP 4, is there a fucntion that counts the files in a given directory? You can assume there are no sub-directories within this directory and hence, no files within the sub-directories. Thanks for any functions or one-liners. - Dave
3
3423
by: umut.tabak | last post by:
Dear all, We have a multi-platform application(Windows-Linux). Linux part of our application is writing some input and trigger files on the a shared drive. What I want to do is to be able to count the occurence of these trigger files. lets say my file is file.start
0
7805
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7751
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4943
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3440
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1874
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
700
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.