Python converts json to csv and the problem of blank lines appears

Article Directory

1. Question:

When I used json to csv, I found that there was a blank line in the middle of each row of data, so I found the reason here.

The data involved has been blurred. Look at the blank line in the middle of the data on the left:
Insert picture description here

Solution:

When saving as csv, add one newline=''to solve this problem, for example:with open('./data_csv.csv','w',encoding='utf-8',newline='')

The complete code below:

import json
import csv


def json_to_csv():
    '''json转csv'''
    with open('./data.json','r',encoding='utf-8') as file:
        cont1 = json.load(file)
        print(type(cont1[0]))
        keys = cont1[0].keys()
        values = [i.values() for i in cont1]

    print("values",values)
    # 会出现空行
    # with open('./data_csv.csv','w',encoding='utf-8') as file1:
    # 不出现空行
    with open('./data_csv.csv','w',encoding='utf-8',newline='') as file1:
        csv_wrie = csv.writer(file1)
        csv_wrie.writerow(keys)
        csv_wrie.writerows(values)

    print('ok')

if __name__ == '__main__':
    json_to_csv()

Schematic diagram of the effect: there are no blank lines on the left. At this time, if you use excel to import csv, there will be no blank lines.
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42081389/article/details/107950019