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
hypersonics
  • 1,064
  • 2
  • 10
  • 23
  • 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 – adifire Feb 12 '15 at 01:07

2 Answers2

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.

Community
  • 1
  • 1
adifire
  • 610
  • 9
  • 23
  • 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. – hypersonics Feb 12 '15 at 02:16
  • 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. – adifire Feb 12 '15 at 23:56
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'>
John Mee
  • 50,179
  • 34
  • 152
  • 186
  • 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. – hypersonics Feb 12 '15 at 01:18