I have a text file named datos.txt
with numeric values, like so:
2
5
1
I read it with the following code:
datos = []
with open ("datos.txt") as fichero:
for dato in fichero.read():
datos.append(dato)
This reads each line as a string. Then I try to convert each element of the data list to numeric, like this:
for dato in datos:
numero = int(dato)
print (numero)
This should work, but I get the following error:
ValueError: invalid literal for int() with base 10: '2\n3'
Why does that error occur? How can I convert that data which is str
to int
? I am using the Python 3 IDLE