Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 7, 2022 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnyman/c3d2093bc78e5b2cc4be623a3c73133f to your computer and use it in GitHub Desktop.
Save gnyman/c3d2093bc78e5b2cc4be623a3c73133f to your computer and use it in GitHub Desktop.
import sys
# create a dictionary to store the size of each directory
sizes = {}
# initialize the current directory to the root
current_dir = '/'
# read the input file
with open(sys.argv[1], 'r') as input_file:
# iterate over the lines in the file
for line in input_file:
# split the line on whitespace, excluding the $ symbol
command, *args = line.strip().split(' ')[1:]
# if the command is "cd", update the current directory
if command == 'cd':
current_dir = args[0]
# if the command is "ls", update the sizes dictionary
# with the sizes of the files in the current directory
elif command == 'ls':
for file in args:
# split the file name and size
name, size = file.split()
# if the current directory is not in the dictionary,
# add it and initialize its size to 0
if current_dir not in sizes:
sizes[current_dir] = 0
# add the size of the file to the size of the current directory
sizes[current_dir] += int(size)
# print the total size of each directory
for directory, size in sizes.items():
print(f'{directory}: {size}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment