Click here to Skip to main content
15,880,469 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()

read.close()
print(aList)
But I'm getting this error.

Traceback (most recent call last):
File "WriteInList.py", line 17, in <module>
aList.append(int(line.strip()))
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.
Posted
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:
Python
for line in read:
    try:
        num = int(line.strip())
        aList.append(num)
    except:
        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