How to count files in a current directory in Python?

Written by Administrator on Sunday May 17, 2020

In order to count files in current directory (where your python script is located), you can run following code:

import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]

number_of_files = 0
for f in files:
    number_of_files += 1

print(number_of_files)

In order to show, how many files located in currect directory, I've used linux command ls. And then I started python script to show, how it counts the number of files in directory.

In definition of "files" variable you can see several python commands, combined into one row: os.listdir() provides the list of files in location you provide (in our case: '.' as a current directory), then we have to be sure, that we count only files and not sub-directories. To do that we have to loop files object and count it.

This is output:

ls
dics.py  files.py  levyi  levyi.py  test01.py  translitgeo.py

python files.py
6

Keep in mind, that files is a list. In case you don't know, which type is a variable you create, you can use type method and then check in official Python documentation, how to work with it. In our case we can check it very easy:

import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]

print(type(files))

and get following output:

<type 'list'>