简体   繁体   中英

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, eg something like this:

id
id
id
...
id

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM