简体   繁体   中英

How to sort data of a file in python(windows)

We are trying to implement a file based student record program.We want to sort the file that contain the details of the student according to the roll number which is at the first position of every line.

the file contains the following data:

1/rahul/cs
10/manish sharma/mba
5/jhon/ms
2/ram/bba

We want to sort the file's data according to the first field ie roll number.

Any help shall be great

You use sorted :

dataSorted = list(sorted(f.readlines()))

If you want to sort only the first element use:

dataSorted = list(sorted(f.readlines(), lambda line: line[:line.find('/')]))

f is the file-object. Further information: help(sorted)

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