用Python删除多余的行

时间:2018-12-07 13:34:16

标签: python

我正在编写一个Python程序,以便在Python中将数据写入CSV。这是我的下面的代码

from pandas.io.json import json_normalize
import json
import csv

data =[
    {
        "Name": "jonathan",
        "Age": 23,
        "Occupation": "Lawyer",
        "Address":[
            {"postal_code":2323,
             "place": "TP",
             "Location":"Central Singapore"

            }
        ]      

    },
    {
        "Name": "jacky",
        "Age": 21,
        "Occupation": "IT analyst",
        "Address":[
            {"postal_code":31234,
             "place": "CCK",
             "Location":"NW Singapore"

            }
        ]
    }
]

nested_json = data
new_dict= dict()

# to flatten the json
def flatten_json(nested_json):
    out = {}
    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(nested_json)
    return out

# function to get the data out and flatten and write to csv
def write_to_csv(nested_json):
    for i in nested_json:
        a = flatten_json(i)
        print(a)
        with open('dict.csv', 'w', newline='') as csv_file:
            writer = csv.writer(csv_file)
            writer.writerow(a.values())

if __name__ == '__main__':
    write_to_csv(nested_json);

问题是我打开的csv在每行数据之后写了一个空行。

我关注了这个stackoverflow问题,以解决(CSV file written with Python has blank lines between each row

,但似乎不起作用。因此,还有一种替代方法是在处理后使用熊猫删除空白行,但这似乎有点愚蠢。如此,请问我在做什么错?我确保换行符=''。

非常感谢您

1 个答案:

答案 0 :(得分:0)

我设法弄清楚出了什么问题。

请在此处参考修订后的代码。我将解决问题。

from pandas.io.json import json_normalize
import json
import csv

data =[
    {
        "Name": "jonathan",
        "Age": 23,
        "Occupation": "Lawyer",
        "Address":[
            {"postal_code":2323,
             "place": "TP",
             "Location":"Central Singapore"

            }
        ]      

    },
    {
        "Name": "Adrian",
        "Age": 21,
        "Occupation": "IT analyst",
        "Address":[
            {"postal_code":31234,
             "place": "CCK",
             "Location":"NW Singapore"

            }
        ]
    }
]

nested_json = data
new_dict= dict()

# to flatten the json
def flatten_json(nested_json):
    out = {}
    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(nested_json)
    return out

# recursiveness to get the data out and flatten
def write_to_csv(nested_json):
    with open('dict.csv', 'a', newline='') as csv_file:
        writer = csv.writer(csv_file)
        for i in nested_json:
            a = flatten_json(i)
            print(a)
            writer.writerow(a.values())

if __name__ == '__main__':
    write_to_csv(nested_json);