Skip to content

Instantly share code, notes, and snippets.

@leninhasda
Created April 19, 2018 11:25
Show Gist options
  • Save leninhasda/0414792e7d65f526ce078f7af932b5af to your computer and use it in GitHub Desktop.
Save leninhasda/0414792e7d65f526ce078f7af932b5af to your computer and use it in GitHub Desktop.
Simple python script to count files in directory.
#!/usr/bin/env python
import os, sys
def countFilesRecursive(dirname):
cnt = 0
for file in os.listdir(dirname):
fullpath = os.path.join(dirname, file)
if os.path.isdir(fullpath):
cnt = cnt + countFilesRecursive(fullpath)
elif os.path.isfile(fullpath):
cnt = cnt + 1
return cnt
def main():
dir_list = []
if len(sys.argv) > 1:
dir_list = sys.argv[1:]
else:
dir_list = ["./"]
for dir in dir_list:
if os.path.isfile(dir):
print("\"{}\" is not a directory!".format(dir))
continue
dirname = "current"
if dir not in ["./", "."]:
dirname = dir
print("Total {} files in {} directory".format(countFilesRecursive(dir), dirname))
if __name__ == '__main__':
main()
@leninhasda
Copy link
Author

leninhasda commented Apr 19, 2018

Usage:

Copy the content and save in a file. (ex: count-files.py or just download it)
Now you should be able to run it like this:

python count-files.py . # current directory (default)
python count-files.py . dir_2 /home/lenin # count files in current directory, dir_2, and /home/lenin directory

# or do this
chmod +x count-files.py
sudo mv /usr/local/bin/count-files

# then from anywhere in terminal
count-files ~/Downloads # count files in Download directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment