9 Kim Cheol-soo 72
10 Park Jae-yong 79
1 Na Young-hee 34
3 Lee Nayeon 46
I read the text file (class number, name, grade) in this way and based on the class number, After organizing them in descending or ascending order, I need to print it back to the file What should I do?
java file-io
If the file is not a flat file that follows a strict format, but a loose format, you should use a regular expression... Fortunately, it's a file of 'class', 'name' and 'sex' that can be separated by 'text' and '\n' line breaks...
#text.txt
9 Kim Chul-soo 72
10 Park Jaeyong 79
1. Na Younghee 34
3 NAYEON 46
filename = 'text.txt'
f = open(filename,'r', encoding='utf-8')
counter = 0
subCounter = 0
studentNumber = ''
studentName = ''
studentGrade = ''
studentList = []
while(True):
try:
temp = f.readline()
if temp == '':
raise
for i in temp:
if i == ' ' and subCounter == 0:
studentNumber = temp[:counter]
temp = temp[counter+1:]
counter = 0
subCounter += 1
continue
if i == ' ' and subCounter == 1:
if temp[-1] == '\n':
temp = temp[:-1]
studentName = temp[:counter]
studentGrade = temp[counter+1:]
temp = ''
counter = 0
subCounter = 0
studentList.append([studentNumber,studentName,studentGrade])
break
counter+=1
except:
f.close()
break
def sortKey(x):
return int(x[0])
studentList.sort(key=sortKey)
#SaveStudent...
filename2 = 'save.txt'
f2 = open(filename2, 'w', encoding='utf-8')
subCounter2 = 0
for student in studentList:
for i in student:
if subCounter2 == 0:
f2.write(str(i)+' ')
subCounter2 +=1
continue
if subCounter2 == 1:
f2.write(str(i)+' ')
subCounter2 +=1
continue
if subCounter2 == 2:
f2.write(str(i)+'\n')
subCounter2 =0
continue
f2.close()
Python's code is like the above.
© 2024 OneMinuteCode. All rights reserved.