Convert True/False value read from file to boolean
I'm reading a
True - False value from a file and I need to convert it to boolean. Currently it always converts it to
True even if the value is set to
MWE of what I'm trying to do:
with open('file.dat', mode="r") as f: for line in f: reader = line.split() # Convert to boolean <-- Not working? flag = bool(reader) if flag: print 'flag == True' else: print 'flag == False'
file.dat file basically consists of a single string with the value
False written inside. The arrangement looks very convoluted because this is a minimal example from a much larger code and this is how I read parameters into it.
flag always converting to
bool('False') always return
True because strings 'True' and 'False' are not empty.
To quote a great man (and Python documentation):
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
- zero of any numeric type, for example,
- any empty sequence, for example,
All other values are considered true -- so objects of many types are always true.
bool function uses the standard truth testing procedure. That's why you're always getting
To convert a string to boolean you need to do something like this:
def str_to_bool(s): if s == 'True': return True elif s == 'False': return False else: raise ValueError # evil ValueError that doesn't tell you what the wrong value was
★ Back to homepage or read more recommendations: