Sobes.tech
Middle — Senior

SOLID‑refactoring: transforming FileStatManager

livecode

Task condition

It is necessary to bring the FileStatManager class in line with SOLID principles. Responsibilities need to be separated, moving file system operations and user interactions into separate modules so that each class is responsible only for its part of the functionality.

import csv
import os
import shutil

class FileStatManager:
    def __init__(self):
        self.txt_stat = FileStats('txt')
        self.csv_stat = FileStats('csv')

    def read_txt_stats(self, file_path):
        with open(file_path, 'r') as f:
            lines = f.readlines()
            self.txt_stat.increase(lines=len(lines))
        print('TXT stats were updated.')

    def read_csv_stats(self, file_path):
        with open(file_path, 'r') as f:
            reader = csv.reader(f)
            lines = list(reader)
            self.csv_stat.increase(lines=len(lines), columns=min(len(l) for l in lines))
        print('CSV stats were updated.')

    def choose_file(self):
        while True:
            file_path = input('Enter a path to a file you want to count:')
            if os.path.isfile(file_path):
                break
            else:
                print('You entered a wrong path. Try again.')

        if file_path.endswith('.txt'):
            self.read_txt_stats(file_path)
        elif file_path.endswith('.csv'):
            self.read_csv_stats(file_path)

    def clean_stats(self):
        while True:
            answer = input('Are you sure? (y/n)')
            if answer == 'y':
                self.txt_stat = FileStats('txt')
                self.csv_stat = FileStats('csv')
                print('Stats were cleaned')
                break
            elif answer == 'n':
                print('Stats were preserved')
                break

    def show_stats(self):
        print('TXT stats:')
        print(self.txt_stat)
        print('CSV stats:')
        print(self.csv_stat)

    def clean_folder(self):
        while True:
            folder_path = input('Enter a path to a folder you want to clean:')
            if os.path.isdir(folder_path):
                break
            else:
                print('You entered a wrong path. Try again.')

        while True:
            answer = input('Are you sure? (y/n)')
            if answer == 'y':
                try:
                    shutil.rmtree(folder_path)
                    print('Folder was cleaned')
                    break
                except Exception as e:
                    print('Something went wrong. Try again.')
            elif answer == 'n':
                print('Folder was preserved')
                break