将CSV数据读取为词典并再次保存在另一个CSV中

时间:2018-03-18 22:43:24

标签: json python-3.x csv parsing dictionary

我的csv中的数据有两列sha和commit

sha commit
a06d16359ca3b529aea42ca4d84f9a4fc99de0dd {'author': {'name': 'Katrina Owen', 'email': 'kytrinyx@github.com', 'date': '2018-03-09T15:08:39Z'}, 'committer': {'name': 'GitHub', 'email': 'noreply@github.com', 'date': '2018-03-09T15:08:39Z'}, 'message': 'Merge pull request #989 from europ/doc_fix\n\nCommand example fix in documentation.', 'tree': {'sha': 'd472f9d110f0f3c766c23902e7dc466ad9cb101a', 'url': 'https://api.github.com/repos/octokit/octokit.rb/git/trees/d472f9d110f0f3c766c23902e7dc466ad9cb101a'}, 'url': 'https://api.github.com/repos/octokit/octokit.rb/git/commits/a06d16359ca3b529aea42ca4d84f9a4fc99de0dd', 'comment_count': 0, 'verification': {'verified': True, 'reason': 'valid', 'signature': '-----BEGIN PGP SIGNATURE-----\n\nwsBcBAABCAAQBQJaoqN3CRBK7hj4Ov3rIwAAdHIIAF7dma2a+9suqB/dUTZl23hP\nvYmfUSpt+62r0Kwi8HIHrxy9yHgiTQ6VqwvOeTsbNzDhVlqD6wcB4V3Eyyhq4j9K\nu7r3OtKdRD4FFqZDjMnUgKSAADFssFKM6txG0+l4+jtoP+KdBqSb6X/5F+iBTrCw\nROjDly/EAv9FGoxzhrPPlm46Q2GWQ3dGPH4KZpvhZRiLuZsESbjXhIzRR/QqmlrF\n/gKmPhg59rsYOkymGF4MpEQs4U9PNYTfv9F6hdRGaTj4utQXz3Bojuet+qZhWYfp\ntAhi2Q/Mp7TKHsGAWv5yZ3HHdKPSDFYO7jhkWFbQ106UTJUXnBHlSdN0HtfEJ/I=\n=8CFd\n-----END PGP SIGNATURE-----\n', 'payload': 'tree d472f9d110f0f3c766c23902e7dc466ad9cb101a\nparent 86362b9ea392bb88a9041a7d31b58e779ba8459b\nparent 08b226ea40f15547195338827bb277686385b944\nauthor Katrina Owen <kytrinyx@github.com> 1520608119 -0700\ncommitter GitHub <noreply@github.com> 1520608119 -0700\n\nMerge pull request #989 from europ/doc_fix\n\nCommand example fix in documentation.'}}

我需要提交提交列中的数据,如作者[name],commiter [name] 知道如何在从csv文件中读取数据后解析它?

这是代码

commit_link = Request(commit_urls,headers={'Accept': 'application/vnd.github.v3+json'}) 
        response = urlopen(commit_link) 
        commit_json = response.read().decode("utf-8")
        commit_data = json.loads(commit_json)
        # open a file for writing
        commit_file = open('raw_commit_data.csv', 'w',encoding='utf-8')
        # create the csv writer object
        csvwriter = csv.writer(commit_file)
        count = 0
        for commit in commit_data:
            if count == 0:
                header = commit.keys()
                csvwriter.writerow(header)
                count += 1
            csvwriter.writerow(commit.values())
        commit_file.close()  

1 个答案:

答案 0 :(得分:1)

你应该解析JSON ,而不是在事后操纵文件。

FirstPrime