Advertisement
dex95

Untitled

Dec 7th, 2022
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. import os
  2. import shutil
  3.  
  4.  
  5. def sum_of_dir(path):
  6.     for root, dirs, files in os.walk(path):
  7.         size = 0
  8.         for file in files:
  9.             with open(os.path.join(root, file), 'r') as f:
  10.                 size += int(f.readline())
  11.         for dir in dirs:
  12.             size += sum_of_dir(os.path.join(root, dir))
  13.         return size
  14.  
  15.  
  16. with open('input1.txt', 'r') as f:
  17.     rows = list(map(lambda x: x.strip(), f.readlines()))
  18.  
  19.     my_cwd = os.getcwd()
  20.     home = os.path.join(my_cwd, 'tmp')
  21.     if os.path.exists(home):
  22.         shutil.rmtree(home)
  23.     os.mkdir(home)
  24.  
  25.     current_position = home
  26.  
  27.     for row in rows:
  28.         if row.startswith('$'): # command
  29.             command = row.strip('$ ')
  30.             parts = command.split(' ')
  31.             if parts[0] == 'cd':
  32.                 target = parts[1]
  33.                 if target == '..':
  34.                     folders = current_position.split('\\')
  35.                     current_position = '\\'.join(folders[:-1])
  36.                 else:
  37.                     if target == '/':
  38.                         target = home
  39.                     current_position = os.path.join(current_position, target)
  40.             elif parts[0]:
  41.                 continue
  42.         else:
  43.             if row.startswith('dir'):
  44.                 name = row.split()[1]
  45.                 os.mkdir(os.path.join(current_position, name))
  46.             else:
  47.                 size, file_name = row.split()
  48.                 with open(os.path.join(current_position, file_name), 'w') as f:
  49.                     f.write(size)
  50.  
  51.  
  52.  
  53.  
  54.  
  55.     directory_size = {}
  56.     for root, dirs, files in os.walk(home):
  57.         this = root.split('\\')[-1]
  58.         size = 0
  59.         for file in files:
  60.             with open(os.path.join(root, file), 'r') as f:
  61.                 size += int(f.readline())
  62.         for dir in dirs:
  63.             size += sum_of_dir(os.path.join(root, dir))
  64.         directory_size[this] = size
  65.    
  66.     res = 0
  67.     for key, val in directory_size.items():
  68.         if val <= 100000:
  69.             res += val
  70.  
  71.     print(res)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement