How do I order a text file in descending order?


So far I have tried with these examples and I have not been able to solve it:


I get an error:


AttributeError: '_io.TextIOWrapper' object has no attribute 'sort'

with this:




AttributeError: 'str' object has no attribute 'sorted'

with this I do not write anything in the output file:


Thanks for your help

asked by Kwyjibo 26.07.2018 в 15:42

1 answer


First, I will assume that you want to order the file lines according to lexicographic order (as strings), otherwise you will need to apply the appropriate casting to each line before ordering.

The cause of not working tells you the error in the first two cases:

  • In the first code you try to use the so-called sort method of linea1 , where línea1 is the open file, an object _io.TextIOWrapper and that therefore does not have this method. Note that if you follow the Python style rules sort is a method that acts in-place so it will only be defined, if it is, for mutable objects such as lists.

  • In the second case you try to use the so-called sorted method on a string (because it's just that, a string with the name or path of your file). str does not have that defined method either. sorted if that is a prebuilt function that accepts any iterable and returns a list of items ordered.

  • In the third case, you use sorted correctly on a string (not on your file), so at the end you would write in your file the following line XUTTSONNLIFEEDDDAA.- which are the characters sorted lexicographically by "ENDEUDADOS-FINAL.TXT" and this when the GC closes the file and the buffer is emptied, since you do not close the file explicitly and the changes may not be reflected immediately.

The simple solution is to effectively use the builtin sorted and pass the file (which is iterable thanks to readline ). It is good practice to always explicitly close an open file with open using the close method or use with that will do it for you:

with open("ENDEUDADOS.txt") as in_file, open("ENDEUDADOS2.TXT","w") as out_file:
    out_file.writelines(sorted(in_file, reverse=True)) 
answered by 26.07.2018 / 17:53