newWithPython
newWithPython

Reputation: 883

How to sort alphabetically a .txt file with python?

I have a .txt file like with lots of ids liket this:

SDFSD_23423432_SDFSDF
SHTHWREWER_234324_werew
dsdfdsf_334DSFGSDF_w
....
SASFSD3452345_$534253

How can I create an alphabetical sorted version of this file?. This is what I tried:

f=open(raw_input("give me the file"))
for word in f:
    l = sorted(map(str.strip, f))
    print "\n",l
    a = open(r'path/of/the/new/sorted/file.txt', 'w')
    file.write(l)

But I get this exception:

 line 6, in <module>
    file.write(l)
TypeError: descriptor 'write' requires a 'file' object but received a 'list'

How can I fix this in order to create a new alphabeticaly sorted file with a new line per line, e.g. something like this:

id
id
id
...
id

Upvotes: 1

Views: 640

Answers (1)

Neel
Neel

Reputation: 21317

The problem is, you are refering internal file object

>>> file
<type 'file'>
>>> file.write([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'write' requires a 'file' object but received a 'list'

You have to write in your file object which you created in code.

a = open(r'path/of/the/new/sorted/file.txt', 'w')
a.write(str(l))

Upvotes: 1

Related Questions