How to get python to recognize string value in DBF as part of if/else statements?

StackOverflow https://stackoverflow.com/questions/20526066

  •  31-08-2022
  •  | 
  •  

Pergunta

I am building a program to write new values to a dbf based on different conditions but I am having an issue with python not recognizing text values as a part of if/else statements.

if I have "col1" filled with true/false values and I want to say:

my_table.add_fields('col2 N(2,0)')

for record in dbf.Process(my_table):
    if record.col1 == 'true':
        record.col2 = 1
    else: 
        record.col2 = 2

How do I get python to recognize 'true/false' as a value as a part of that statement?

Foi útil?

Solução

What data type is col1? Basic dbf data types are Char (text), Date (datetime), Logical (boolean) Number (integer/float), Float (integer/float), and Memo (unbounded text).

If col1 is not a Char field, comparing to a string will always return False. If col1 is a Char field, then it will compare equal only when col1 is excatly 'true' -- not 'true ' or 'True' or 'TRUE'.

If the problem is extra spaces (by default my module returns the entire field, including trailing spaces) you can either do:

if record.col1.strip() == 'true':

or tell dbf.Table to use a custom Char type that ignores trailing spaces:

my_table = dbf.Table('/path/to/file', default_data_types={'C':dbf.Char})
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top