Teo Jie Wei
Teo Jie Wei

Reputation: 109

Error in reading a file in python

I am trying to obtain some data send in a text file from another machine.

while(1):
    try:
            with open('val.txt') as f:
                    break
    except IOError as e:
            continue

f=open("val.txt","r")
counter = f.read()
print counter
f.close()
counter=int(counter)

On the first execution, it return an error

    counter=int(counter)
    ValueError: invalid literal for int() with base 10: ''

But if I try to execute the program again, I'm able to obtain the data. Please help and thank you=)

UPDATE: Thank to Ashwini comment, I am able to solve the issue. I will leave my solution here for other to reference.

After f.close(), I uses a try-exception method to counter away the empty string issue. Apparently once the file just reach it destination, the data inside the file is still empty.

while(1):
    try:
            counter= int(counter)
            break
    except ValueError:
            f=open("val.txt","r")
            counter = f.read()
            f.close()
            continue

Guess this not an effective method to write a program but it still solve the issue.

Upvotes: 0

Views: 157

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174748

Simply add this:

counter = f.read()
f.close()
if counter.strip():
   counter = int(counter)
   print counter

It will prevent printing if the file is empty, and unless you have characters that can't be converted into numbers, you won't get any more errors.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

Your file is empty and for invalid/empty strings int() raises this error.

In [1]: int("")

ValueError: invalid literal for int() with base 10: ''

In [2]: int("abc")

ValueError: invalid literal for int() with base 10: 'abc'

In [3]: int("20")
Out[3]: 20

You can wrap the int() call around try-except to fix this:

try:
    print int("")
except ValueError:
    print "invalid string"

invalid string

#another example 

try:
    print int("23")
except ValueError:
    print "invalid string"

23

Upvotes: 2

Related Questions