-1

This is my text file. I want to sort second column by ascending order. How do I sort this in python code?

Test file content:

ghj sfs
dtj fsf
zzz hdh
abc kdk
bcd jdd
csf jkd
sfa aaa
ser jld
afr zzz
awr kld
fas ljl
afr lfl
faw kks
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
  • 1
    Read it as a pandas dataframe and sort it with `sort_values()`. Does this answer your question? [how to sort pandas dataframe from one column](https://stackoverflow.com/questions/37787698/how-to-sort-pandas-dataframe-from-one-column) – David Erickson Jul 11 '20 at 08:56
  • 2
    **1.** Read file content. **2.** Sort lines in ascending order using `sorted()` with custom `key` argument. **3.** Re*(?)*write result. – Olvin Roght Jul 11 '20 at 08:57
  • does pandas method is only option to sort columns? your mentioned text file like same to my question. i don't know about pandas concept to write program.Is there any option to sort column in python? – Chezhiyan STR Jul 11 '20 at 09:02
  • You may think about accepting an answer to reward those how helped you, or at least comment to explain what's missing ;) – azro Jul 19 '20 at 12:51

1 Answers1

-1

You may do

# Read
with open("filename.txt") as fic:
    lines = [line.rstrip().split() for line in fic] # read each line

# Sort
lines = sorted(lines, key=lambda x:x[1])

# Write again
with open("filename.txt", "w") as fic:
    fic.writelines([" ".join(line) + "\n" for line in lines]) # write each line

Other way to read

lines = []
with open("filename.txt") as fic:
     for line in fic:
        line = line.rstrip().split()
        lines.append(line)

Other way to write

with open("filename.txt", "w") as fic:
    for line in lines:
        fic.write(" ".join(line) + "\n")
azro
  • 53,056
  • 7
  • 34
  • 70