-3

Additionally, if I wanted to sort them by their age, how could I do so? I tried myFile.sort(), but it crashes the code saying "Object has no attribute 'sort' "

fileName = "GuestList.csv"
ACCESSMODE = "w"
name = " "
nbrGuest = " "

myFile = open(fileName, ACCESSMODE)
nbrGuest = input("How many guests do you have? ")
for index in range (int(nbrGuest)) :
    name = input("Enter guest name: " ).capitalize()
    age = input("Enter guest age: " )
    myFile.write(name + "," + age  + "\n")
myFile.close()
Pynbbz
  • 3
  • 2
  • you would have to store them in some kind of container first, then sort them and finally write them to file. After writing them to the file you cannot sort them. – Ma0 Jul 20 '16 at 07:53
  • 1
    @RoadRunner, the OP is not opening an existing file: `input` is used (twice) and that input information should be stored. – Nander Speerstra Jul 20 '16 at 07:54
  • @RoadRunner It's supposed to create the new file, every time a new list of names from user input. I just want to sort it by name or age so later I can show the complete list. – Pynbbz Jul 20 '16 at 07:55
  • @Ev.Kounis Ok that makes sense, thing is I'm just learning to code, can you tell me how to do that? thank you very much – Pynbbz Jul 20 '16 at 07:56

2 Answers2

1

So the code is now split into two parts.

fileName = "GuestList.csv"
ACCESSMODE = "w"
name = " "
nbrGuest = " "


nbrGuest = input("How many guests do you have? ")
guest_list = []
for index in range(int(nbrGuest)):
    name = input("Enter guest name:\t").capitalize()
    age = input("Enter guest age:\t")
    guest_list.append((name, age))

guest_list.sort(key=lambda x: x[1])
with open(fileName, ACCESSMODE) as myFile:
    for guest in guest_list:
        myFile.write(guest[0] + "," + guest[1] + "\n")

The first part takes the user input and stores all information in a list of tuples. Each tuple looks like e.g., ('ALEX', '24'). After the list of guests is complete, it is sorted in place using the .sort() method based on the age of the guests (youngest first, use the ,reverse=True to reverse the order). Finally, the sorted names and ages are written to file that is managed by the with statement so that you don't have to worry about closing it or flushing it.

Ma0
  • 15,057
  • 4
  • 35
  • 65
-1

Duplicate question : sort-csv-by-column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

Note that only the list in the variable will be sorted, not the file. Youl'll have tto sort the list first then write the file in a second time.

Community
  • 1
  • 1
Leogiciel
  • 263
  • 2
  • 10