Search code examples
pythontuplesdbf

Python - Strip each element of a Tuple


I am retrieving data from a DBF file and I need to generate a SQL script to load the data into a database. I already have this but the values are stored in a tuple and before i create the SQL script I want to strip each item of the tuple. For example, I am getting this:

INSERT INTO my_table (col1,col2,col3) VALUES('Value 1     ', 'TESTE123', '  ADAD ')

And I need to get this:

INSERT INTO my_table (col1,col2,col3) VALUES('Value 1', 'TESTE123', 'ADAD')

For that I am trying with this code:

with dbf.Table(filename) as table:
            for record in table:
                fields = dbf.field_names(table)
                fields = ','.join(fields)
                place_holders = ','.join(['?'] * len(fields))
                values = tuple(record.strip())
                sql = "insert into %s (%s) values(%s)" & ('my_table', fields, values)

And I am getting the following error: dbf.FieldMissingError: 'STRIP' no such field in table

What do you purpose?


Solution

  • dbf.Record is not a str, and doesn't have string methods.

    If every field in the record is text (e.g. Character or Memo, not Numeric or Date) then you can:

    values = [v.strip() for v in record]