disk space analysis hackerrank python
To perform disk space analysis in Python, you can use the built-in os
module to get information about the files and directories in the system.
Here is an example implementation of disk space analysis using the os
module:
pythonimport os
def get_directory_size(path='.'):
total = 0
with os.scandir(path) as it:
for entry in it:
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += get_directory_size(entry.path)
return total
def get_file_sizes(path='.'):
file_sizes = {}
with os.scandir(path) as it:
for entry in it:
if entry.is_file():
file_sizes[entry.name] = entry.stat().st_size
elif entry.is_dir():
sub_sizes = get_file_sizes(entry.path)
for sub_file, sub_size in sub_sizes.items():
file_sizes[os.path.join(entry.name, sub_file)] = sub_size
return file_sizes
# Example usage
directory_size = get_directory_size('.')
print(f"Total size of current directory: {directory_size} bytes")
file_sizes = get_file_sizes('.')
for file, size in file_sizes.items():
print(f"{file}: {size} bytes")
The get_directory_size
function recursively iterates through all files and directories in a given path, accumulating the file sizes along the way. The function returns the total size of all files in the directory.
The get_file_sizes
function also recursively iterates through all files and directories in a given path, but instead of accumulating the file sizes, it creates a dictionary of file names and sizes. The dictionary includes the file sizes of all files in the directory and its subdirectories, with the keys being the full file paths.
You can call these functions with the path to the directory you want to analyze. For example, calling get_directory_size('/usr/local')
will return the total size of all files in the /usr/local
directory.