computing codes

Sorting numbers in each row of a table – Python code

Reading – sorting – writing to a file (Python code)

Details:

Name: SortByRow.py (Python 3.10.0)
Description: The code will open a text file called “infile.txt” and read the content of the file, which is a table of numbers. Next, each row of this table is sorted in ascending order. The new table is then written to a new text file called “outfile.txt”.

# SortByRow.py
import numpy as np

inf = "infile.txt"      # input file name
outf = "outfile.txt"    # output file name
de = "\t"               #delimiter used in infile.txt (tab)
de2 = ", "              #delimiter used in outfile.txt 

# read the first row as dummy row for use with vstack
f = open(inf, "rt")
str1 = f.readline().strip()
if str1 != '':
   str2 = str1.split(de)
   row = np.array(str2)
   irow = row.astype(int)
   imat = irow
   omat = irow 
f.close()

f = open(inf, "rt")
while True:
    str1 = f.readline().strip()
    if str1 == '':
        break
    else:
        str2 = str1.split(de)
        row = np.array(str2)
        irow = row.astype(int)
        imat = np.vstack((imat,irow))   
f.close()
    
imat = imat[1:,:] #remove dummy row

'''
sorting each row in imat in ascending order
results stored in omat
'''
for x in imat:
    omat = np.vstack((omat,np.sort(x)))

omat = omat[1:,:] # remove dummy row

# write sorted row to a new output file, numbers separated by a comma 

f2 = open(outf,"w")
for x in omat:
    for a in x[0:-1]:
       f2.write("%s" % a+de2)
    f2.write("%s\n" % x[-1])
f2.close()

Content of input file “infile.txt”

3	38	18	41	39	1
11	32	16	41	21	39
26	27	41	1	10	24
1	32	36	42	2	8
16	26	14	5	17	33
38	17	23	29	30	32
3	24	8	23	35	19
11	22	29	18	19	36
19	24	28	1	31	39
3	29	38	32	30	31
21	39	41	26	16	9
1	22	42	24	32	39

Content of output file “outfile.txt”

1, 3, 18, 38, 39, 41
11, 16, 21, 32, 39, 41
1, 10, 24, 26, 27, 41
1, 2, 8, 32, 36, 42
5, 14, 16, 17, 26, 33
17, 23, 29, 30, 32, 38
3, 8, 19, 23, 24, 35
11, 18, 19, 22, 29, 36
1, 19, 24, 28, 31, 39
3, 29, 30, 31, 32, 38
9, 16, 21, 26, 39, 41
1, 22, 24, 32, 39, 42