|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def read_file():
result = []
with open("students.txt", encoding="UTF-8") as fin:
for line in fin:
line = line[:-1]
result.append(line.split(","))
return result
def sort_grades(datas):
return sorted(datas,
key=lambda x : int(x[2]),
reverse=True)
def write_files(datas):
with open("students_output.txt", "w", encoding="UTF-8") as fout:
for data in datas:
fout.write(",". join(data) + "\n")
datas = read_file()
print("read_file datas:", datas)
datas = sort_grades(datas)
print("sort_grades datas:", datas)
write_files(datas)
print("write_files datas:", datas)
C:\Users\Administrator\AppData\Local\Programs\Python\Python39\python.exe C:\Users\Administrator\Desktop\CODE\lianxi2.py
read_file datas: [['101', '小张', '88'], ['102', '小赵', '99'], ['103', '小孙', '55'], ['104', '小李', '77'], ['105', '小王','6']]
sort_grades datas: [['102', '小赵', '99'], ['101', '小张', '88'], ['104', '小李', '77'], ['103', '小孙', '55'], ['105', '小王', '6']]
write_files datas: [['102', '小赵', '99'], ['101', '小张', '88'], ['104', '小李', '77'], ['103', '小孙', '55'], ['105', '小王', '6']]
Process finished with exit code 0
最后一行没有换行就没有换行符,所以 line = line[:-1] 把最后一个字符去掉了
你可以把 line = line[:-1] 替换成 line = line.rstrip()
def read_file():
result = []
with open("students.txt", encoding="UTF-8") as fin:
for line in fin:
line = line.rstrip() # 改了这行
result.append(line.split(","))
return result
def sort_grades(datas):
return sorted(datas,
key=lambda x : int(x[2]),
reverse=True)
def write_files(datas):
with open("students_output.txt", "w", encoding="UTF-8") as fout:
for data in datas:
fout.write(",". join(data) + "\n")
datas = read_file()
print("read_file datas:", datas)
datas = sort_grades(datas)
print("sort_grades datas:", datas)
write_files(datas)
print("write_files datas:", datas)
|
|