Get in touch!Get in touch!

Sorting a list using python

Let us suppose you have a text file that contains a list of several items, and you want to sort it in alphabetical order. The following script will help you to accomplish that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/python
 
#sort_script.py
#Author: Victor Miti
#Tested with python 2.6.8 and 2.7.5
 
'''-----------------------------Description--------------------------------'''
#This python script reads the specified text file, sorts it in alphabetical
#order and writes a sorted copy of the original file to disk.
'''------------------------------------------------------------------------'''
 
import sys, datetime
 
#get the current time
now = datetime.datetime.now()
 
#Input File
input_file = "point_descriptors.txt"
 
#Output Filename Prefix
output_file_prefix = input_file.strip(".txt")+"(sorted_"
 
#redirect stdout to a .txt file in the same directory
#we want the filename to have a timestamp
sys.stdout = open(output_file_prefix+now.strftime("%Y%m%d~%H%M%S")+").txt", "w")
 
#Open the file and read the contents line by line
open_file = open(input_file, "r")
lineList = open_file.readlines()
 
#Sort the lines in alphabetical order, ignoring case & deleting newlines ('\n')
lineList.sort(key=lambda s: s.lower())
for line in  lineList:
    print(line.rstrip('\n'))
 
#close the file
open_file.close
#!/usr/bin/python

#sort_script.py
#Author: Victor Miti
#Tested with python 2.6.8 and 2.7.5

'''-----------------------------Description--------------------------------'''
#This python script reads the specified text file, sorts it in alphabetical
#order and writes a sorted copy of the original file to disk.
'''------------------------------------------------------------------------'''

import sys, datetime

#get the current time
now = datetime.datetime.now()

#Input File
input_file = "point_descriptors.txt"

#Output Filename Prefix
output_file_prefix = input_file.strip(".txt")+"(sorted_"

#redirect stdout to a .txt file in the same directory
#we want the filename to have a timestamp
sys.stdout = open(output_file_prefix+now.strftime("%Y%m%d~%H%M%S")+").txt", "w")

#Open the file and read the contents line by line
open_file = open(input_file, "r")
lineList = open_file.readlines()

#Sort the lines in alphabetical order, ignoring case & deleting newlines ('\n')
lineList.sort(key=lambda s: s.lower())
for line in  lineList:
    print(line.rstrip('\n'))

#close the file
open_file.close


Leave a Reply