python count files and display max -


i tying count al file extenties in directory. , count them , display how many of them there. best way make this? script gonna big al pdf= 0 lines of code.
how can display output of how many files there are, high lower.

import os  pdf = 0 doc = 0 docx = 0 xls = 0 xlsx = 0 ppt = 0 pptx = 0  file in os.listdir("c:\\users\\joey\\desktop\\school\\icommh"):     if file.endswith(".pdf"):         pdf += 1         print(file)     if file.endswith(".doc"):         doc += 1         print(file)     if file.endswith(".docx"):         docx += 1         print(file)     if file.endswith(".xls"):         xls += 1         print(file)     if file.endswith(".xlsx"):         xlsx += 1         print(file)     if file.endswith(".ppt"):         ppt += 1         print(file)     if file.endswith(".pptx"):         pptx += 1         print(file)  print(pdf) print(doc) print(docx) 

you use dictionary:

import os  exts = {} my_exts = ('pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx')  file in os.listdir("c:\\users\\joey\\desktop\\school\\icommh"):     ext = os.path.splitext(file)[1]     if ext , ext[1:] in my_exts:         exts[ext] = exts.get(ext, 0) + 1  print sorted(exts.items(), key=lambda x: x[1], reverse=true) 

the output be:

[('.doc', 4), ('.pdf', 2), ('.xlsx', 1)]


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -