Sort TXT lines in numerical order

Asked

Viewed 410 times

0

I need to invert all the columns of my txt file, using python. txt file (example):

Regra n10 - exemplo
Regra n9 - exemplo
Regra n8 - exemplo
Regra n7 - exemplo
Regra n6 - exemplo
Regra n5 - exemplo
Regra n4 - exemplo
Regra n3 - exemplo
Regra n2 - exemplo
Regra n1 - exemplo

As I said, I need to reverse, getting:

Regra n1 - exemplo
Regra n2 - exemplo
Regra n3 - exemplo
Regra n4 - exemplo
Regra n5 - exemplo
Regra n6 - exemplo
Regra n7 - exemplo
Regra n8 - exemplo
Regra n9 - exemplo
Regra n10 - exemplo

There’s already a numerical order, it’s just reversed, I just need to change the order of all the lines, reverse the order of all. I’m using the Python 2.7!

  • 3

    the files are exactly as you are showing? You want to learn and understand how this works programmatically, or simply want someone to solve your problem?

  • The file is well simulated, I just need to invert all, because there is already a numerical order, it is just reversed. I would just like a solution, because I will only use this once.

1 answer

1


If it fits in memory it is very simple. You read all the lines of the file, and then go over them in reverse order.

arquivo = open("nomearquivo.txt", "r")
conteudo = arquivo.readlines()
arquivo.close()
arquivo_saida = open("novoarquivo.txt","w")
for linha in conteudo[::-1]:
    arquivo_saida.write(linha)
arquivo_saida.close()
  • You’re a genius! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.