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
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
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")