What is a convenient way to store and retrieve boolean values in a CSV file
If I store a boolean value using the CSV module it gets converted to the strings 'True' or 'False' by the str() function. However when I load those values, a string of 'False' evaluates to being True because it's a non-empty string.
I can work around it by 'manualy' checking the string at read time with an IF statement to see what the string is, but it's somewhat less than elegant. Any better ideas, or is this just one of those things in the programming world?
I don't think this is possible with Python's csv
module. However...
By saying that you both write and read the CSV file from Python, you're admitting to be using a CSV file for some kind of data serialization. Why would you want to do that? There's plenty of better options for serializing Python data, and CSV files should IMHO be reserved for interaction with other tools that require them for some reason.
use the int() function to covert the boolean to their int values and then store those. that being said, eli-bendersky's comment above is worth noting.
I'm not sure if answering your own question is bad form or not, but here's the solution I've come up with. It basicaly consists of hiving off that pesky IF statement I was talking about into a function.
def setyesNo(value):
if value: return 'Yes'
else: return 'No'
def checkYesNo(text):
if text == 'Yes': return True
else: return False
Then in my dictWriter do this.
for item in mylist:
writer.writerow( {'Is Cool' : setYesNo(item.is_cool),
.....
})
And in dictReader.
for line in reader:
item MyObject(is_Cool=checkYesNo(line['Is Cool']),
.....
)
mylist.append(item)
链接地址: http://www.djcxy.com/p/47840.html