''' >>> from testing import run, diff >>> run('python monthly_temperatures.py data/Brno_daily.csv data/Brno_monthly.csv', __name__) # doctest: +NORMALIZE_WHITESPACE ══════════════════════════════════════════════════════════════════════════ $ python monthly_temperatures.py data/Brno_daily.csv data/Brno_monthly.csv ────────────────────────────────────────────────────────────────────────── ══════════════════════════════════════════════════════════════════════════ Srovnání s očekávaným výstupním souborem: >>> diff('data/Brno_monthly-expected.csv', 'data/Brno_monthly.csv') Files are identical ''' import argparse from pathlib import Path import csv import statistics def main() -> None: # Načtení argumentů z příkazového řádku pomocí argparse parser = argparse.ArgumentParser(description='Calculate average monthly temperatures.') parser.add_argument('input', help='Input CSV file with daily temperatures', type=Path) parser.add_argument('output', help='Output CSV file with monthly temperatures', type=Path) args = parser.parse_args() # Načtení tabulky with open(args.input, encoding='utf8', newline='') as r: reader = csv.reader(r) table = list(reader) # Načteme celou tabulku table = table[4:] # Odstraníme první 4 řádky # Zpracování dictionary = {} # Klíče budou roky, hodnoty seznamy měsíčních teplot for row in table: year, month, *temps = row year = int(year) temps = [float(t) for t in temps if t != ''] # Odstraníme prázdné buňky a konvertujeme teploty na float mean_temp = round(statistics.mean(temps), 1) if year not in dictionary: dictionary[year] = [] dictionary[year].append(mean_temp) # Výpis tabulky with open(args.output, 'w', encoding='utf8', newline='') as w: writer = csv.writer(w) header = ['', *range(1, 13)] writer.writerow(header) for year, temps in dictionary.items(): row = [year, *temps] writer.writerow(row) if __name__ == '__main__': main()