So currently I'm using the code seen below to calculate the size of all the files in a directory. this works fine for my uses. just wondered if there was a way to make it get the total file size of specific file types such as .py files or .txt.
total_file = sum(os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f))
Answer
To calculate the total file size for specific file types like .py
or .txt
, you can filter the files in your directory based on their extension before summing their sizes. You can use os.path.splitext()
to get the file extension and check if it matches the desired types.
Here's an updated version of your code that calculates the total size for specific file types:
import os
# Define the file types you're interested in
file_types = ('.py', '.txt')
# Calculate the total file size for the specified file types
total_size = sum(os.path.getsize(f) for f in os.listdir('.')
if os.path.isfile(f) and f.endswith(file_types))
print(f"Total size of .py and .txt files: {total_size} bytes")
Explanation:
os.listdir('.')
: Lists all files in the current directory.os.path.isfile(f)
: Ensures that we are only looking at files (not directories).f.endswith(file_types)
: Checks if the file ends with one of the specified extensions (e.g.,.py
,.txt
).os.path.getsize(f)
: Gets the size of each file.
Customizing the file types:
You can easily adjust the file_types
tuple to include any other file extensions you're interested in, for example, ('.py', '.txt', '.csv')
.
This will give you the total size of only the files with those specific extensions.