2 Replies - 657 Views - Last Post: 10 November 2015 - 10:27 PM Rate Topic: -----

#1 XxRepti1exX   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 10-September 15

Read from text file error.

Posted 10 November 2015 - 09:07 PM

Ok I wrote some code to give 5-7 numbers with odd range between 5-19 to a file.

Example output:

13
5
7
7
17
15


I want to read this text in a straight line and total it.
Example output:


13 5 7 7 17 15
Numbers in file add up to 64


This is my code
def main():
    # Open a file for reading.
    num_file = open('numbers.txt', 'r')

    # Read three numbers from the file.
    num1 = int(num_file.readline(1))
    num2 = int(num_file.readline(2))
    num3 = int(num_file.readline(3))
    num4 = int(num_file.readline(4))
    num5 = int(num_file.readline(5))
    num6 = int(num_file.readline(6))
    num7 = int(num_file.readline(7))

    # Close the file.
    num_file.close()

    # Add the numbers.
    total = num1 + num2 + num3 + num4 + num5 + num6 + num7

    # Display the numbers and their total.
    print('The numbers are:', num1,num2,num3,num4,num5,num6,num7)
    print('Their total is:', total)


main()





My error is num2 = int(num_file.readline(2))
ValueError: invalid literal for int() with base 10: '\n'



All and any help is appreciated as always you guys are great thanks in advance!! A ton!!!

Is This A Good Question/Topic? 0
  • +

Replies To: Read from text file error.

#2 jon.kiparsky   User is offline

  • Beginner
  • member icon


Reputation: 11768
  • View blog
  • Posts: 19,977
  • Joined: 19-March 11

Re: Read from text file error.

Posted 10 November 2015 - 09:51 PM

num1 = int(num_file.readline(2)


I'm not sure what you think the argument to this function is doing, but it's not doing what you think it's doing. Start by getting rid of the argument.

That will produce a failure on the first readline() call. This is because you'll be actually getting the whole first line, instead of the first byte of it - this includes the trailing newline character which lives at the end of each line in a text file (on a well-behaved system, at least) and is spelled "\n" if you're a computer.

Since this is not a digit, the input can't be parsed as an integer. Can you think of a way to get rid of unwanted whitespace from the end of a string?
Was This Post Helpful? 0
  • +
  • -

#3 XxRepti1exX   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 10-September 15

Re: Read from text file error.

Posted 10 November 2015 - 10:27 PM

Sorry for the wait on the reply but I'm having issues with the site :) Yes you can strip('n/')?

How and where would I incorporate that in?



Also on different web browsers firefox and edge I'm having issues with the website it needs some debugging from you ;)


All I know is that "trackAdView" is undefined
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1