0

I am trying to load a text file that has two column data, separated by a tab. The first column values could be either integers or floats, while the second column will always be floats. Now, I am using isinstance to see if my first column is integer or float. However, isinstance doesn't seem to work when a list of values or the final element of the list is used. This is my code:

time_t = []
with open(logF, 'r') as f:
    for line in f:
        data_t = line.split()
        time_t.append(data_t[0])

time_length_max = time_t[-1]
print time_length_max

if isinstance(time_length_max, (int, long)):
   print "True"
 else:
   print "False"

The output I get is:

10000
False

Suppose, I declare time_length_max = 10000, instead of time_length_max = time_t[-1], I get:

10000
True
1
  • This looks like more of a conversion issue at the time of reading the file, generally it retrieves the value in the form of strings. So that is likely the case here Commented Feb 12, 2015 at 1:07

2 Answers 2

1

You can try this as suggested in

https://stackoverflow.com/a/379966/350429

def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

time_t = []
with open(logF, 'r') as f:
    for line in f:
        data_t = line.split()
        time_t.append(num(data_t[0]))

time_length_max = time_t[-1]
print time_length_max

if isinstance(time_length_max, (int, long)):
   print "True"
 else:
   print "False"

Beware that the value should be a number in the file, if it is an empty string then it will throw an exception.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @adifire. Your approach works fine. However, it fails when I check the entire list. For example, instead of time_length_max in if isinstance(time_length_max, (int, long)), If I use if isinstance(time_t (int, long)), it prints False indicating floats. However, my time_t is a list of 1 to 10000, all of which are integers.
Well actually isinstance(time_t, (int,long)) will return false because it is a list, not because it is a float or anything. To check for the whole list, you would have to check the type of individual values in time_t.
0

split returns strings. You probably want to cast your string to an integer before asking if it is an instance of an integer.

>>> type('10000')
<type 'str'>
>>> type(10000)
<type 'int'>
>>> type(int('10000'))
<type 'int'>

1 Comment

Thanks @JohnMee. While, int('10000') works if the value is integer, but fails when its float. I did this: time_t.append(int(data_t[0])). This worked fine for the case when time_t was an integer, but failed for a float value.

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.