Click here to Skip to main content
15,946,342 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm try to read lines in a text file (number.txt) and write into a List.

My code block:

read = open('number.txt')

# use readline() to read the first line

line = read.readline()
# use the read line to read further.
# If the file is not empty keep reading one lineat a time, till the file is empty

aList = []

while line:

aList.append(int(line.strip())) #Line 17 is Here
line = read.readline()

But I'm getting this error.

Traceback (most recent call last):
File "", line 17, in <module>
ValueError: invalid literal for int() with base 10: ''

What I have tried:

I used strip()
I searched about that, however I could not figure out.
Updated 28-Aug-18 2:49am

1 solution

It tells you that the line contains text that can't be converted to an int. strip() will only remove leading and trailing white spaces.

To handle such cases you can use try - except:
for line in read:
        num = int(line.strip())
        print "Not a number in line " + line
Note that I have changed the while loop to a for loop on the file object because that is more efficient.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900