0
how to sort a file
I joined a line in a file and trying to sort the file based on the first word. I used f.sort but it is showing str object has no attribute. Here is the code that I followed. t_l = '' with open('t.txt') as f: f.sort(); out = [x for x in f.read().split("\n") if x.strip() != ""] for line1, line2 in list(zip(out, out[1:]))[::2]: line1 = line1 + ';' line2 = line2.split(' ') line = '' for x in range(1,len(line2)): line = line + line2[x] + ' ' line = line[:-1] + '.' t_l += " ".join([line1, line]) + '\n' with open('new.txt' , 'w') as file: file.write(t_l) Please help where I am going wrong. Any help would be appreciated.
2 Respuestas
+ 4
I think you can use readline() instead of read, to get the lines. Append each line to a list and then sort it. It will be sorted anyway, so after that you can .join and .write
+ 4
I hope that i have understood you right. See the result: (sorting is taking the complete line. If you strictly want to use only the first word, the code has to be extended to this)
#the file contained:
'''
Paris France
Brussels Belgium
Stockholm Sweden
Berlin Germany
Rome Italy
'''
buf = []
for i in open('input.txt'):
buf.append(i.strip())
buf.sort()
# list buf after sorting:
'''
Berlin Germany
Brussels Belgium
Paris France
Rome Italy
Stockholm Sweden
'''