将json-ish列表逐行写入csv,在python中逐行写入比特币地址

时间:2016-09-03 14:44:32

标签: python json csv bitcoin

我正在查询onename api以获取所有用户的比特币地址。

目前我将所有用户信息作为json-esque列表,然后将输出汇总到一个文件,它看起来像这样:

[{'0': {'owner_address': '1Q2Tv6f9vXbdoxRmGwNrHbjrrK4Hv6jCsz', 'zone_file': '{"avatar": {"url": "https://s3.amazonaws.com/kd4/111"}, "bitcoin": {"address": "1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh"}, "cover": {"url": "https://s3.amazonaws.com/dx3/111"}, "facebook": {"proof": {"url": "https://facebook.com/jasondrake1978/posts/10152769170542776"}, "username": "jasondrake1978"}, "graph": {"url": "https://s3.amazonaws.com/grph/111"}, "location": {"formatted": "Mechanicsville, Va"}, "name": {"formatted": "Jason Drake"}, "twitter": {"username": "000001"}, "v": "0.2", "website": "http://1642.com"}', 'verifications': [{'proof_url': 'https://facebook.com/jasondrake1978/posts/10152769170542776', 'service': 'facebook', 'valid': False, 'identifier': 'jasondrake1978'}], 'profile': {'website': 'http://1642.com', 'cover': {'url': 'https://s3.amazonaws.com/dx3/111'}, 'facebook': {'proof': {'url': 'https://facebook.com/jasondrake1978/posts/10152769170542776'}, 'username': 'jasondrake1978'}, 'twitter': {'username': '000001'}, 'bitcoin': {'address': '1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh'}, 'name': {'formatted': 'Jason Drake'}, 'graph': {'url': 'https://s3.amazonaws.com/grph/111'}, 'location': {'formatted': 'Mechanicsville, Va'}, 'avatar': {'url': 'https://s3.amazonaws.com/kd4/111'}, 'v': '0.2'}}}]

我真正感兴趣的是字段{"address": "1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh"},其余的东西我不需要,我只想要每个用户的地址。

有没有办法只使用python将地址写入文件?

我正在尝试将其写成:

1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh,
1GA9RVZHuEE8zm4ooMTiqLicfnvymhzRVm,
1BJdMS9E5TUXxJcAvBriwvDoXmVeJfKiFV,
1NmLvYVEZqPGeQNcgFS3DdghpoqaH4r5Xh,
...

等等。

我使用dumpdumps等尝试了多种不同的方法,但我还没有把它固定下来。

我的代码如下所示:

import os
import json
import requests
#import py2neo
import csv


# set up authentication parameters
#py2neo.authenticate("46.101.180.63:7474", "neo4j", "uni-bonn")

# Connect to graph and add constraints.
neo4jUrl = os.environ.get('NEO4J_URL',"http://46.101.180.63:7474/db/data/")
#graph = py2neo.Graph(neo4jUrl)

# Add uniqueness constraints.
#graph.run("CREATE CONSTRAINT ON (q:Person) ASSERT q.id IS UNIQUE;")

# Build URL.
apiUrl = "https://api.onename.com/v1/users"
# apiUrl = "https://raw.githubusercontent.com/s-matthew-english/26.04/master/test.json"

# Send GET request.
Allusersjson = requests.get(apiUrl, headers = {"accept":"application/json"}).json()

#print(json)])
UsersDetails=[]
for username in Allusersjson['usernames']:
    usernamex= username[:-3]
    apiUrl2="https://api.onename.com/v1/users/"+usernamex+"?app-id=demo-app-id&app-secret=demo-app-secret"
    userinfo=requests.get(apiUrl2, headers = {"accept":"application/json"}).json()
    # try:
    #     if('bitcoin' not in userinfo[usernamex]['profile']):
    #         continue
    #     else:
    #         UsersDetails.append(userinfo)
    # except:
    #     continue
    try:
        address = userinfo[usernamex]["profile"]["bitcoin"]["address"]
        UsersDetails.append(address)
    except KeyError:
        pass  # no address

out = "\n".join(UsersDetails)
print(out)
open("out.csv", "w").write(out)

# f = csv.writer(open("test.csv", "wb+"))


# Build query.
query = """
RETURN {json}
"""

# Send Cypher query.
# py2neo.CypherQuery(graph, query).run(json=json)
# graph.run(query).run(json=json)

#graph.run(query,json=json)

无论如何,在这种情况下,将这些地址写成csv的最佳方法是什么:/

更新

我跑了,起初它有效,但后来我收到了以下错误: enter image description here

2 个答案:

答案 0 :(得分:1)

而不是将所有信息添加到UsersDetails列表

UsersDetails.append(userinfo)

您只需添加相关部分(地址)

try:
    address = userinfo[usernamex]["profile"]["bitcoin"]["address"]
    UsersDetails.append(address)
except KeyError:
    pass  # no address
except TypeError:
    pass  # illformed data

要将值打印到屏幕:

out = "\n".join(UsersDetails)  
print(out)

(替换" \ n"用","对于逗号分隔的输出,而不是每行一个)

要保存到文件:

open("out.csv", "w").write(out)

答案 1 :(得分:1)

您需要通过map()或列表理解重新格式化列表,以便将其归结为您想要的信息。例如,如果api.onename.com API的响应中使用的顶级键始终为0,则可以执行以下操作

UsersAddresses = [user['0']['profile']['bitcoin']['address'] for user in UsersDetails]