tags:

views:

49

answers:

3

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?

+3  A: 

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.

Eli Bendersky
Users should be able to view and manupulate the data in the Python application or Excel interchangeably, with work flows going back and forth between the two.
Simon Hibbs
@Simon: do you offer real Excel interoperability or is it just for editing simple values? It's hard to imagine your Python app allowing anything more complex than that, in which case you don't really need excel but can present the data to the users in a simple editable table created with some Python GUI framework
Eli Bendersky
I have a table view in the Python app, but there are pre-existing Excel tools for this kind of data and the users of the data are highly likely to be familiar with Excel and want to use it. there also pre-existing database apps for this kind of data and I need to be able to have a path to interoperability with them as well. CSV seems to me to be a reasonable intermediate format.
Simon Hibbs
A: 

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.

tjboring
I considered that, but the value stored in the CSV file needs to be easily parseable by the human eye. If I was just storing it for machine processing I wouldn't be using a CSV file and Eli's comment would be spot on.
Simon Hibbs
A: 

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)
Simon Hibbs