从while循环读取的文件中删除\ n

时间:2015-05-18 22:35:35

标签: python

这是我下面的代码,它主要输出我想要的内容,但它包含\ n在每个数字之后,我不知道如何摆脱它...任何帮助?谢谢!

def main():
    scores = []
    scores_file = open('scores.txt', 'r')
    line_list = list(scores_file.readlines())
    print(line_list)
    i = 0
    while i < len(line_list):
        scores.append(line_list[i])
        i += 1


main()

3 个答案:

答案 0 :(得分:1)

with open('scores.txt', 'r') as f:
    scores = [int(line.strip()) for line in f]

答案 1 :(得分:1)

with open('scores.txt') as f:
    scores = f.read().splitlines()

答案 2 :(得分:0)

如果你想保持while循环(你不应该这样做)

def main():
    scores = []
    scores_file = open('scores.txt', 'r')
    line_list = scores_file.readlines()
    scores_file.close()
    i = 0

    while i < len(line_list):
        scores.append(int(line_list[i].strip()))
        i += 1
    print(scores)

main()

如果您发现列表理解有点难以理解,可以将其分解为这样的实际循环。

def main():
    scores = []
    with open('scores.txt') as f:
        for line in f:
            scores.append(int(line.strip()))
    print(scores)

你可以避免使用列表索引变量i以及所有错误的可能性和可能性。