【发布时间】:2021-07-05 16:56:13
【问题描述】:
我在 stackoverflow 上的第一篇文章,并试图通过编写一个从我玩的在线游戏的 API 调用数据的程序来涉足 python :)
我编写了下面的代码来创建一个 .csv 文件(如果它不存在),然后使用 for 循环调用 API 两次(每次都有不同的匹配 ID)。响应是 JSON 格式的,思路是如果文件为空(即新建),则执行 if 语句写入 headers,如果不为空(即 headers 已写入),则写入值。
我的代码返回一个 .csv,其中标头写入了两次 - 因此,由于某些原因,在 for 循环中,即使标头已被写入,文件大小也不会改变。我在这里缺少什么吗?非常感谢!
import urllib.request, urllib.parse, urllib.error
import json
import csv
import ssl
import os
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
api_key = 'XXX'
puuid = 'XXX'
matchlist = ['0e8194de-f011-4018-aca2-36b1a749badd','ae207558-599e-480e-ae97-7b59f97ec8d7']
f = csv.writer(open('my_file.csv','w+'))
for matchid in matchlist:
matchdeturl = 'https://europe.api.riotgames.com/lor/match/v1/matches/'+ matchid +'?api_key=' + api_key
matchdetuh = urllib.request.urlopen(matchdeturl, context = ctx)
matchdet = json.loads(matchdetuh.read().decode())
matchplayers = matchdet['info']
#if file is blank, write headers, if not write values
if os.stat('my_file.csv').st_size == 0:
f.writerow(list(matchplayers))
f.writerow(matchplayers.values())
else:
f.writerow(matchplayers.values())
【问题讨论】:
标签: python python-3.x csv