os.path.getsize(path) returns the size of the file or filesystem object identified by a pathname. section 12.3
Use it when traversing files and accumulating sizes:
- Pass the file path to os.path.getsize and add the returned value to a running total. section 12.6.2
- Combine it with os.walk, os.path.islink, and extension checks to measure selected files while excluding symlinks. section 12.6.2
- Use pathlib.Path.stat().st_size for a pathlib-based alternative. section 12.3 section 12.6.2
Total the sizes of .test files
import os total_size = 0 for root, _, files in os.walk('.'): for file in files: path = os.path.join(root, file) if file.endswith('.test') and not os.path.islink(path): total_size += os.path.getsize(path) print(f"Total size of .test files: {total_size} bytes") section 12.6.2
import pathlib
cur_path = pathlib.Path("sample_data")
size = 0
for text_path in cur_path.rglob("*.test"): #1
if not text_path.is_symlink(): #2
size += text_path.stat().st_size #3
print(size)
Compare the pathlib form, which obtains the same size through text_path.stat().st_size after recursively finding matching files. section 12.6.2
