I was wondering how I can find the number of files I have in a certain folder. For example in this file containing about 1000 excel files:
from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")
Thanks.
I was wondering how I can find the number of files I have in a certain folder. For example in this file containing about 1000 excel files:
from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")
Thanks.
You could use .glob()
or .rglob()
:
from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")
excelFiles = fileDir.rglob('*.xl*')
print(len(list(excelFiles)))
>>> 3
You can use this:
import os
import glob
files = 0
folder_path = 'your path'
for filename in glob.glob(os.path.join(folder_path, '*.xls')): # .xls for example
files += 1
Here's a little function I put together that will list all the files in a given folder. You can then use the length of the list to see how many there are, or loop though the list if you want to do anything with them:
import os
def list_files(folder, extensions=None):
file_list = []
all_files = os.listdir(folder)
for name in all_files:
if extensions is not None:
for ext in extensions:
if name.endswith(ext):
file_list.append(f'{folder}{os.sep}{name}')
else:
file_list.append(f'{folder}{os.sep}{name}')
return file_list
if __name__ == '__main__':
all_files = list_files('C:/Users/Jonas/Desktop/Test')
print('total files: ')
print(len(all_files))
all_excel_files = list_files('C:/Users/Jonas/Desktop/Test', ['xlsx', 'xls', 'xlsm'])
print('excel files:')
print(len(all_excel_files))
If you need the number of all files, you could do something like this:
from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")
print(len[f for f in fileDir.iterdir()])
If you need to filter on the name, you can add a condition on f.name
or use fileDir.glob()
or fileDir.rglob()
, like the others suggested. E.g,
from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")
print(len[f for f in fileDir.iterdir() if len(f.name) < 10])
import os
os.system('ls /etc | wc -l')
https://devconnected.com/how-to-count-files-in-directory-on-linux/