close

How to keep null values when writing to csv

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to keep null values when writing to csv in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to keep null values when writing to csv?

  1. How to keep null values when writing to csv?

    uses writer as-is, but you don't have to do that. You can filter the values to change some particular values with a generator comprehension and a ternary expression

  2. keep null values when writing to csv

    uses writer as-is, but you don't have to do that. You can filter the values to change some particular values with a generator comprehension and a ternary expression

Method 1

your code

for row in self.cursor:
    csv_writer.writerow(row)

uses writer as-is, but you don’t have to do that. You can filter the values to change some particular values with a generator comprehension and a ternary expression

for row in self.cursor:
    csv_writer.writerow("null" if x is None else x for x in row)

Method 2

You are asking for csv.QUOTE_NONNUMERIC. This will turn everything that is not a number into a string. You should consider using csv.QUOTE_MINIMAL as it might be more what you are after:

Test Code:

import csv

test_data = (None, 0, '', 'data')
for name, quotes in (('test1.csv', csv.QUOTE_NONNUMERIC),
                     ('test2.csv', csv.QUOTE_MINIMAL)):

    with open(name, mode='w') as outfile:
        csv_writer = csv.writer(outfile, delimiter=',', quoting=quotes)
        csv_writer.writerow(test_data))

Results:

test1.csv:

"",0,"","data"

test2.csv:

,0,,data

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read