0

I have been trying to create a program which asks for a name and an age and stores them to a text file. My code is as follows:

name_age=open('Name Age.txt','a')
print('1. Writing to a text file')
print('2. Reading a text file')
print('3. Sorting')
Choice=int(input('What do you want to do: '))

if Choice==1:
    Name=input('What is the Name: ')
    Age=int(input('What is the age: '))
    Name_Age=Name,Age
    name_age.write(repr(Name_Age),'\n')
    print('Written result')
if Choice==2:
    name_age=open('Name Age.txt','r')
    print('Reading the file')
    print(name_age.read(1000))
if Choice==3:
    print('Sorting')
    print('1. Alphabetical')
    print('2. Age')
    Choice=int(input('How do you want to sort(1/2): '))
    if Choice==1:
        print('Sorting Alphabetically')
        print(sorted(name_age))
    if Choice==2:
        print('Help Me HERE')
    #I Need Help here... How do you sort the textfile with the ages???

Then my code has the ability to allow the user to read the file from the program and sort the results. I can sort the results alphabetically but I cannot sort them in age order. Can you please help me do this

  • Instead of 'name_age.write(repr(Name_Age),'\n')' you can use 'name_age.write("{},{}\n".format(Name, Age))'. No need of expr. – shantanoo May 13 '15 at 19:51
  • Not *exactly* duplicate, but definitely related, and very likely useful: http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort – John Y May 13 '15 at 21:21

2 Answers2

2

You'd have to show us the structure of your file, but if it's something like

bob 18
steve 28
mike 39
tom 22

You could do

print(sorted(name_age, key = lambda i : int(i.split()[1])))

This works by splitting each line on whitespace, converting it to an int, then sorting by the number in element [1] instead of the first element which is their name.

Edit:
With the format Hanzalah, 14 you would use

print(sorted(name_age, key = lambda i : int(i.split(',')[1])))

Edit 2:
To sort highest to lowest, use the reverse argument

print(sorted(name_age, key = lambda i : int(i.split(',')[1]), reverse=True))
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

You could use a dictionary reader (DictReader) from the csv module to separate reading the input file contents and processing its contents. We use a lambda function to provide flexibility in choosing which field to sort by. Assuming the same format as @Cyber, you can use the following example.

#Sample input file, eg, /tmp/sample.csv
name,age
bob,12
annie,20
suzie,5
wrothgar,15

Here's the bit of code:

import csv

# You can change the path to your file accordingly
finput = file("/tmp/sample.csv",'r')

# Usually good to have this explicitly. You can use comma or tab, etc
delimiter=','

# Remove new line, then split the first line into the two fields
header = finput.readline().strip().split(delimiter) 

# Let's create our reader, and extract the entries in the file
reader = csv.DictReader(finput, fieldnames=header, delimiter=delimiter)
entries = [entry for entry in reader]

# Perform additional type checking for your input and even cast the 'age' value here instead of in the lambda function below

# Let's sort using sorted its two parameters 'key' and 'reverse'
sorted(entries, key=lambda entry: int(entry['age']))  # Sort using the age field
sorted(entries, key=lambda entry: int(entry['age']), reverse=True) # Sort using the age field, in reverse order
sorted(entries, key=lambda entry: entry['name']))  # Sort using the name field

Hopefully this gives you intuition on using the 'key' parameter of sorted where the comparator of the sorted function uses the value passed to 'key'. Using the utility classes of the csv module should help out with other data processing projects, e.g., DictWriter.

Goodluck!

Paul Rigor
  • 986
  • 1
  • 12
  • 23