- 1 year ago
Compare files size between the source and the target folder in python
Comment
1 / 1
To compare file sizes between a source and a target folder in Python, you can use the os
module to obtain file information such as size and os.path
to manipulate file paths. Here's an example code snippet to get you started:
pythonimport os
def get_folder_size(folder_path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(folder_path):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
total_size += os.path.getsize(file_path)
return total_size
source_folder = '/path/to/source/folder'
target_folder = '/path/to/target/folder'
source_size = get_folder_size(source_folder)
target_size = get_folder_size(target_folder)
print(f"Source folder size: {source_size} bytes")
print(f"Target folder size: {target_size} bytes")
if source_size > target_size:
print("Source folder is larger than the target folder")
elif source_size < target_size:
print("Target folder is larger than the source folder")
else:
print("Source folder and target folder have the same size")
In this example, the get_folder_size
function recursively walks through the directory tree using os.walk
, calculates the size of each file using os.path.getsize
, and sums up the total size. Then, you can compare the sizes of the source and target folders and print the appropriate message based on the result.
Make sure to replace /path/to/source/folder
and /path/to/target/folder
with the actual paths to your respective folders.