Reputation: 105
In my folder, there are two types of files: html
and txt
.
I want to know the total size of the txt
files.
I found this code, but how do I apply it for my needs?
import os
from os.path import join, getsize
size = 0
count = 0
for root, dirs, files in os.walk(path):
size += sum(getsize(join(root, name)) for name in files)
count += len(files)
print count, size
Upvotes: 1
Views: 730
Reputation: 990
better use glob (https://docs.python.org/3/library/glob.html) instead of os to find your files. that makes it imho more readable.
import glob
import os
path = '/tmp'
files = glob.glob(path + "/**/*.txt")
total_size = 0
for file in files:
total_size += os.path.getsize(os.path.join(path, file))
print len(files), total_size
Upvotes: 2
Reputation: 49794
You can qualify which files by adding an if
to the comprehensions like:
for root, dirs, files in os.walk(path):
size += sum(getsize(join(root, name)) for name in files if name.endswith('.txt'))
count += sum(1 for name in files if name.endswith('.txt'))
print count, size
Upvotes: 2