xiaoxiaosen 发表于 2023-3-6 18:07:28

写读取成绩的代码,但是为啥读出来的TXT不对呢

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),
                  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

xiaoxiaosen 发表于 2023-3-6 18:08:02

最后一个数据读出就是不对的,66的数据读出是6

isdkz 发表于 2023-3-6 18:14:46

最后一行没有换行就没有换行符,所以 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),
                  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)

xiaoxiaosen 发表于 2023-3-6 18:46:27

isdkz 发表于 2023-3-6 18:14
最后一行没有换行就没有换行符,所以 line = line[:-1] 把最后一个字符去掉了

你可以把 line = line[:-1 ...

谢谢
页: [1]
查看完整版本: 写读取成绩的代码,但是为啥读出来的TXT不对呢