Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count number of file in a directory python

Tags:

python-2.7

The following syntax was used to get the number of files in my directory , but can you please help me understand this syntax.( how does ".next()[2]" help in calculating the python.) I am a newbie in python please help me with it.

len(os.walk(path).next()[2])
like image 244
avinash v p Avatar asked Sep 09 '15 07:09

avinash v p


People also ask

How do I count the number of files in a directory?

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1.

How do you count the number of files in a file in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

How do I get a list of files in a directory in Python?

os. listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory.


2 Answers

If you want to understand this syntax, I suggest you decompose it as follows:

os.walk(path) will return a generator (basically an iterator)

<generator object walk at 0x7f5e5acbd4b0>

os.walk is supposed to browse all levels of directories, you're asking for next() to get the first level (and not the subdirectories)

os.walk(path).next()

This will return:

(
    [0] -> The path you passed
    [1] -> list of All the first level directories in your path
    [2] -> list of All the first level files
)

In order to get the files, you'll ask for the element of index [2] in your list

os.walk(path).next()[2]

And finally so you can count the number of these elements, you use len (stands for length)

Here you go:

len(os.walk(path).next()[2])
like image 53
YOBA Avatar answered Nov 07 '22 10:11

YOBA


To count the number of files in a directory you can use listdir() method.

import os
files = os.listdir()
print len(files)
like image 29
trishnag Avatar answered Nov 07 '22 10:11

trishnag