Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

python - How to sort a text file line-by-line

I need to sort a text file in ascending order. Each line of the text file starts with an index, as seen below:

2       0       4         0d 07:00:38.0400009155273
3       0       4         0d 07:00:38.0400009155273
1       0       4         0d 07:00:38.0400009155273   

The idea result would be as follows:

1       0       4         0d 07:00:38.0400009155273
2       0       4         0d 07:00:38.0400009155273
3       0       4         0d 07:00:38.0400009155273 

Please note, this text file has +3 million rows and each element is naturally considered a string.

I've been messing around with this for sometime now without any luck so I figured it was time to consult with the experts. Thank you for you time!

EDIT:

I'm using windows OS with Python 3.7 in Spyder IDE. The file is not a CSV its a text file that is tab delimited. There is the possibility that not all indices are present. Forgive the noob-ness, I haven't got a lot of experience coding.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
fn = 'filename.txt'
sorted_fn = 'sorted_filename.txt'

with open(fn,'r') as first_file:
    rows = first_file.readlines()
    sorted_rows = sorted(rows, key=lambda x: int(x.split()[0]), reverse=False)
    with open(sorted_fn,'w') as second_file:
        for row in sorted_rows:
            second_file.write(row)

This should work for a text file of 3+ million rows. Using int(x.split()[0]) will sort the first item in each row as an integer

Edited to remove close() statements


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...