Reputation: 167
I am trying to read numbers from a file in python. The file contains ONLY numbers. ALl numbers are decimal!! As asked, this is the file contents: 25 4 2 6 7
I get this error:
Traceback (most recent call last):
File "readfile.py", line 18, in <module>
a.append(int(data[i]))
ValueError: invalid literal for int() with base 10: 'f'"
This is my code:
check=0
while(check!=1):
file=raw_input("Plase state the file name:")
print "\n"
try:
check=1
fo=open(file,"r",1)
except IOError:
print "NO such file or directory"
check=0
data=0
a=[]
i=0
for line in file:
data=line.split()
print data
a.append(int(data[i]))
i=i+1
print a
fo.close()
Upvotes: 1
Views: 216
Reputation: 325
How about spliiting the content and looping thru it.
with open('some_file','r') as fo:
content = fo.read().split(" ")
for num in content:
print num
Upvotes: 1
Reputation: 7606
You are doing...
for line in file:
You should be doing...
for line in fo:
Looping the file name string won't help you.
Also, you need to fix the iterator, i
, on the data list. Or instead of fixing the iterator, you could do list comprehension
:
a += [int(x) for x in data]
Upvotes: 2