1

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()
5
  • 1
    Looks like it is running into strings. Include some of the file you are reading? Commented Jun 1, 2014 at 3:51
  • Actually, I don't think the i does what you think it does. it increments for each line, not looping on the split. Commented Jun 1, 2014 at 3:52
  • Ok, but if I do a.append(int(data)), I get an error about trying to pass a list as an int Commented Jun 1, 2014 at 3:54
  • 1
    for num in data: a.append (int (num)) Commented Jun 1, 2014 at 4:03
  • Couldn't format last comment nicely from mobile. Your original code creates a list of the numbers for each line but tries to add the numbers to 'a' using the line as the index rather than the position of the number on the line. Commented Jun 1, 2014 at 4:06

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

3 Comments

It's not. file is a string for your file name according to your code. If you loop that, you are looping the string 1 character at a time. And let me guess, your file starts with the letter f?
Did you do something like data[i]? Or change how you assign data?
It's ok now, I did: for line in fo: data=line.split() a += [int(num) for num in data]
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.