python - How do i sort my text file alphabeticaly yet keep the line spaces -


i have following code:

test=open("newtextdocument.txt", "r") lines1 = (test.readlines()) lines1.sort() print(lines1)` 

and using store text file these contents:

('lars', ' in class', '1', ' has got score of', 8) ('lars2', ' in class', '1', ' has got score of', 1) ('as', ' in class', '1', ' has got score of', 1) ('12', ' in class', '1', ' has got score of', 0) ('lars', ' in class', '1', ' has got score of', 8) ('lars', ' in class', '1', ' has got score of', 8) ('lars', ' in class', '1', ' has got score of', 7, ' time of', 39.79597997665405) ('test', ' in class', '1', ' has got score of', 1, ' time of', 17) 

what want sort lines of file alphabetically yet keep line breaks. example:

('as', ' in class', '1', ' has got score of', 1) ('lars', ' in class', '1', ' has got score of', 8) ('lars2', ' in class', '1', ' has got score of', 1) 

however after running code is:

["('12', ' in class', '1', ' has got score of', 0)\n",  "('as', ' in class', '1', ' has got score of', 1)\n",  "('lars', ' in class', '1', ' has got score of', 7, ' time of', 39.79597997665405)\n",  "('lars', ' in class', '1', ' has got score of', 8)\n",  "('lars', ' in class', '1', ' has got score of', 8)\n",  "('lars', ' in class', '1', ' has got score of', 8)\n",  "('lars2', ' in class', '1', ' has got score of', 1)\n",  "('test', ' in class', '1', ' has got score of', 1, ' time of', 17)"] 

how can fix this?

all you're doing wrong printing list without formatting. printing lines1 spit out long line contents of list. want loop on list , print 1 line @ time:

for line in lines1:     print line, 

i added comma since of lines end newline character anyway, printing trailing comma means wont add newline every time.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -