Nov-05-2018, 08:58 AM
use defaultdict from collections module
1. filter is built-in function, don't use it as variable name
2. no need to iterate over filenames. use list.extend() method instead
3. no need to create new list (with odd name newstr, which suggest it is a str object). If you want the len of the list with all files - just use it
4. you create a function for each extension/file type. Although it's not efficient to iterate over the all-files list each time, you can at least do it with one generic function. just pass second argument - the file extension(s).
from collections import defaultdict import os all_files = defaultdict(list) for root, folders, files in os.walk(r'C:\Users\sai\Desktop\dosc'): for item in files: ext = os.path.splitext(item)[-1][1:] all_files[ext].append(item) for ext, files in all_files.items(): print('Number of {} files: {}'.format(ext, len(files)))That said, let me point some issues with your code
1. filter is built-in function, don't use it as variable name
2. no need to iterate over filenames. use list.extend() method instead
3. no need to create new list (with odd name newstr, which suggest it is a str object). If you want the len of the list with all files - just use it
4. you create a function for each extension/file type. Although it's not efficient to iterate over the all-files list each time, you can at least do it with one generic function. just pass second argument - the file extension(s).
from pathlib import Path def get_files(all_files, extensions): return [item for item in all_files if Path(item).suffix in extensions] all_files = [] for root, folders, files in os.walk(r'C:\Users\BKolev\Desktop'): all_files.extend(files) jpeg_files = get_files(all_files, ['.jpeg', '.jpg']) print('Number of jpeg files: {}'.format(len(jpeg_files)))here I use pathlib module, instead of os.path to show different tools you can use also in the previous snippet
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs