~ Simplest way to sort a file in python - teach yourself python


Sorting files in Python - by specific fields.

Challenge -Sort a file in Python by ID number or any other specific field)

Read the task instructions that are included in the comments in the code, and then get started!

You can either edit and code online in repl.it or alternatively, you can simply cut and paste the below into your own python file

Solve the challenge on repl.it

Code

""" ==============TASK
Several applications will require you to carry out a Sort.

1. Using the existing code below, adapt it to get the program to sort by USER ID (001 first)
2. Print the results to the screen (as a list) (it doesn't need t be necessarily printed back to the file)
"""

import csv

#1. This code snippet sorts the file by index 2 (last name) using lambda

with open('fakefacebook_write.txt','r',newline="") as f: #open the file in read mode
        reader=csv.reader(f)
        sorted_list=list(reader)#turn the reader iterator into a list
        sorted_list.sort(key=lambda x:x[2]) #use index 02 as the column to sort by, in this case last name
        #print(sorted_list) #this will simply print the sorted list --> Below is a prettier (formatted) print
        print("\n".join(str(row) for row in sorted_list))  # prettier print

File Contents

Filename:fakefacebook_write.txt

ID,firstname, lastname,username,password,email,no_of_likes
001,Ruth,Marvin,marvR,pass123,marv@gmail.com,400
002,Carter,Smith,smithC,open123,cart@gmail.com,200
003,Joe,Blogs, blogsJ,2bg123,blog@gmail.com,99
004,Ruth,Pigachee,pigR,pig123,piggy@gmail.com,72


Code your solution here

Systems Life Cycle (in a nutshell): Analyse - Design - Create - Test - Evaluate. Designing something or writing out some pseudocode before you actually write code is always a good idea! Get in to the habit of doing so! You can draw your flowchart here and screenshot it.

A sample flow chart (design) for this particular challenge could look like:

Flowchart: Python program to get the Fibonacci series between 0 to 50
Each challenge section below provides an online drawing tool where you can dynamically create flowcharts. Screenshot them into your presentation for submission.

Solutions & Answers

Answers /Solutions in the "members area" drive under: "Solve and Learn >>SOLUTIONS"

Testing Table

You may want to read a little about Testing first. A teacher may go through some examples with you. Feel free to fill in the test table here, and screenshot it in to your powerpoint. Testing is absolutely essential once you have created a program!
Test No. Description Test Data(input) Expected Outcome Actual Outcome Further Action?
1
2
3
4
5
Coming soon!