1

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

Noah
  • 1,683
  • 14
  • 19
spbiknut
  • 75
  • 1
  • 5
  • Possible duplicate of [How do I keep Python print from adding newlines or spaces?](http://stackoverflow.com/questions/255147/how-do-i-keep-python-print-from-adding-newlines-or-spaces) – Drazisil Nov 21 '15 at 23:11
  • You should put language as a tag (helps getting attention from the right people) – osundblad Nov 21 '15 at 23:19
  • 1
    @Drazisil this would not be a duplicate since here `end` is used in the `print` function which implies that this is Python 3 where `print` is a function and not a statement. The question you referenced is Python 2 where adding a comma at the end of the lists is used to prevent a newline being printed. – Noah Nov 21 '15 at 23:20

1 Answers1

1

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()
Noah
  • 1,683
  • 14
  • 19
  • Noah, thanks for the response. I tried this, but I'm still getting the same output. I'm thinking I need to read the file and build a range out of it before I print it. – spbiknut Nov 21 '15 at 23:36
  • @spbiknut For some reason I had removed `end=''`. You do need to keep that because the default value of `end` if not specified is `\n`. Put that back in your print function and try again. Sorry. – Noah Nov 21 '15 at 23:40
  • Noah, That did it! I understand it now...Thanks for your help! – spbiknut Nov 21 '15 at 23:44
  • Noah, one other question...is there a way to sum those numbers and print the total? – spbiknut Nov 22 '15 at 01:00