spbiknut
spbiknut

Reputation: 75

Printing integers on the same line reading from a text file

Beginner needs some help

My code is below. I'm trying to get the integers to print out on the same line. I'm reading the them from a text file named "numbers.txt". Any help would be greatly appreciated.

def main():
    num_file = open('numbers.txt', 'r')
    for num in (num_file):
        print(num, end='')
    num_file.close()
    print('End of file')

main()

Here is my current output:

enter image description here

Upvotes: 1

Views: 782

Answers (1)

Noah
Noah

Reputation: 1731

When reading a file line by line as you have done here with for num in (num_file), the end of line characters do not get stripped off and are included with each line and stored in your variable num. This is why the numbers continue to print on separate lines even though you set end=''.

You can use rstrip to remove the new line character in addition to setting end=''. Also, the parentheses around num_file in your for loop are not necessary.

def main():
    num_file = open('numbers.txt', 'r')

    for num in num_file:
        print(num.rstrip('\n'), end='')

    num_file.close()
    print('End of file')

main()

To sum the numbers found:

def main():
    num_file = open('numbers.txt', 'r')
    total = 0

    for num in num_file:
        print(num.rstrip('\n'), end='')
        try:
            total = total + int(num)
        except ValueError as e:
            # Catch errors if file contains a line with non number
            pass

    num_file.close()
    print('\nSum: {0}'.format(total))
    print('End of file')

main()

Upvotes: 1

Related Questions