Search code examples
pythonlistcsvtuples

split by comma and ignore if comma in quotes a data from List of Tuples - Python


I have a list of tuples.

lt = [('051623', 'O143', '1.23', '2023-05-16T18:30:00', '1M allen', 'millan'), ('051623', 'O207', '1.23', '2023-05-16T18:35:00', 'nM Mn, 4nM, 35uM Fe', 'wilo')]

Need to convert to csv string by comma separated but while split the commas within quotes to be ignored: Expected is below.

'051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
'051623', 'O207', '1.23', '2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'

I tried but not working:

csv_string = '\n'.join(",".join([element if element else 'None' for element in tup]) for tup in lt)

Solution

  • You can use the csv library:

    lt = [
      ('051623', 'O143', '1.23', '2023-05-16T18:30:00', '1M allen', 'millan'), 
      ('051623', 'O207', '1.23', '2023-05-16T18:35:00', 'nM Mn, 4nM, 35uM Fe', 'wilo'),
    ]
    
    import io
    import csv
    
    
    # Allows saving the csv output to a string instead of a file
    f = io.StringIO(newline='')    
    
    writer = csv.writer(
        f,
        quotechar="'",
        quoting=csv.QUOTE_ALL,
    )
    writer.writerows(lt)
    
    # `getvalue()` returns a string containing the csv output
    print(f.getvalue())
    

    It outputs

    '051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
    '051623','O207','1.23','2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'