I have a file that has 3 values on each line. It is a fairly random file, and any of these values can be str or int.
George, 34s, Nikon
42, absent, Alan
apple, 111, 41
marked, 15, never
...
So, I read in the line, and using split I get the first value:
theFile = r"C:\... "
tDC = open(theFile, "r")
for theLine in tDC:
a, b, c = theLine.split(',')
So far so good.
Where I'm stuck is when I try to deal with variable a
. I need to deal with it differently if it is a str or if it is an int. I tried setting a = int(a)
, but if it is a string (e.g., 'George') then I get an error. I tried if type(a) = int
or if isinstance(a,int)
, but neither work because all the values come in as a string!
So, how do I evaluate the value NOT looking at its assigned 'type'? Specifically, I want to read all the a
's and find the maximum value of all the numbers (they'll be integers, but could be large -- six digits, perhaps).
Is there a way to read in the line so that numbers come in as numbers and strings come in as strings, or perhaps there is a way to evaluate the value itself without looking at the type?
try
/except
block, using theValueError
in theexcept
.42
represents the int42
or the string"42"
? After all, data that can have string values like"32s"
can probably also have string values like"42"
.csv
library instead of manually callingsplit
. I have no idea where your data come from or what they mean, but I wouldn't be too surprised it you ran into a column like"Smith, John"
, which your code will treat that as two columns instead of one, which would be hard to fix, while withcsv
it will either just work, or be a trivial matter of setting a dialect parameter to fix it.