0

I am trying to sort a column from a .txt file. I am going do a point-register system where I am going to save the name of the player and his three laps.

I am saving my values in the text-file like so:

 1. name;lap_1;lap_2;lap_3;
 2. name;lap_1;lap_2;lap_3;
 3. name;lap_1;lap_2;lap_3;

In my code I write them to the file like so:

for result in results:
    my_file.write("{}:{}:{}:{}:{}:{};\n".format(result["name"],
                                                result["lap1"],
                                                result["lap2"],
                                                result["lap3"],
                                                result["total"],
                                                result["average"]))

How do I sort each column, for example "name"? And how do I print it out?

AJF
  • 11,767
  • 2
  • 37
  • 64
aregato
  • 3
  • 1
  • 3
  • See: http://stackoverflow.com/questions/2100353/sort-csv-by-column – sgrg Apr 20 '17 at 21:38
  • I have adjusted your spelling, grammar, and formatting. I would recommend taking time with [learning how to format](http://stackoverflow.com/editing-help), and checking your grammar and spelling carefully, in order to ask better questions in the future. – AJF Apr 22 '17 at 23:00

1 Answers1

1

first of all, as @sgrg suggested, use CSV-file format, e. g. we can write simply with

import csv


def write_results(results, fields_names):
    # or use mode="a" if you want to append
    with open("my_file.csv", mode="w", newline="") as my_file:
        csv_writer = csv.DictWriter(my_file, fieldnames=fields_names, delimiter=";")
        # remember: you don"t need to add headers in "append" mode
        csv_writer.writeheader()
        for result in results:
            csv_writer.writerow(result)

then read with

def read_results(fields_names):
    with open("my_file.csv", mode="r") as my_file:
        # ignoring headers
        next(my_file)
        csv_reader = csv.DictReader(my_file, fieldnames=fields_names, delimiter=";")
        return list(csv_reader)

sorting of results by name can be done with

sorted_results = sorted(results, key=lambda result: result["name"])

usage

fields_names = ["name", "lap1", "lap2", "lap3", "total", "avarage"]
results_tuples = [("Luke", "lap1_value", "lap2_value", "lap3_value", 100, 96.3),
                  ("Stephen", "lap1_value", "lap2_value", "lap3_value", 100, 96.3),
                  ("Adrian", "lap1_value", "lap2_value", "lap3_value", 100, 96.3)]
results = [dict(zip(fields_names, result_tuple)) for result_tuple in results_tuples]
write_results(results,
              fields_names=fields_names)
results = read_results(fields_names)
sorted_results = sorted(results, key=lambda result: result["name"])

in given example results is a list object which looks like

[{'avarage': 96.3,
  'lap1': 'lap1_value',
  'lap2': 'lap2_value',
  'lap3': 'lap3_value',
  'name': 'Luke',
  'total': 100},
 {'avarage': 96.3,
  'lap1': 'lap1_value',
  'lap2': 'lap2_value',
  'lap3': 'lap3_value',
  'name': 'Stephen',
  'total': 100},
 {'avarage': 96.3,
  'lap1': 'lap1_value',
  'lap2': 'lap2_value',
  'lap3': 'lap3_value',
  'name': 'Adrian',
  'total': 100}]

and sorted_results is a list object which looks like

[OrderedDict([('name', 'Adrian'),
              ('lap1', 'lap1_value'),
              ('lap2', 'lap2_value'),
              ('lap3', 'lap3_value'),
              ('total', '100'),
              ('avarage', '96.3')]),
 OrderedDict([('name', 'Luke'),
              ('lap1', 'lap1_value'),
              ('lap2', 'lap2_value'),
              ('lap3', 'lap3_value'),
              ('total', '100'),
              ('avarage', '96.3')]),
 OrderedDict([('name', 'Stephen'),
              ('lap1', 'lap1_value'),
              ('lap2', 'lap2_value'),
              ('lap3', 'lap3_value'),
              ('total', '100'),
              ('avarage', '96.3')])]

More info about csv module at docs

More info about OrderedDict at docs

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50