0

This is my code below and it outputs mostly what I want, but it contains \n after each number and I do not know how to get rid of it...any help? Thanks!

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()
Dzarafata
  • 558
  • 3
  • 11
John Finger
  • 39
  • 2
  • 7

3 Answers3

1
with open('scores.txt', 'r') as f:
    scores = [int(line.strip()) for line in f]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • Thanks for reply! Not working for me, must be doing something wrong. I would place that after the opening of the scores.txt file in main right? – John Finger May 18 '15 at 22:44
  • 1
    This does open the file, remove the other open. It replaces all the code in your `main` function. – Paul Rooney May 18 '15 at 22:49
1
with open('scores.txt') as f:
    scores = f.read().splitlines()
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
0

If you wanted to keep the while loop (which you shouldn't)

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

If you find the list comprehension a little hard to follow it can be broken down to an actual loop like this.

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

You avoid having to have the list index variable i and all the ugliness and possibility for mistakes that go with it.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61