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])
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.
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.
os. listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory.
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])
To count the number of files in a directory you can use listdir() method.
import os
files = os.listdir()
print len(files)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With