我有一个脚本从API中提取信息,并且应该将其写入我在同一目录中的CSV文件中。由于某种原因,所有代码似乎执行正常,但CSV实际上从不包含任何数据。我错过了一些关键的东西吗我已经检查了CSV模块的文档,但找不到任何内容。
这是我的代码:
import time, json, requests, csv
with open('data.csv', 'w') as csvfile:
fieldnames = ['time','last','vwap','high','low','open','vol']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
def btstampTime():
bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/')
return bitStampTick.json()['timestamp']
def btstampLast():
bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/')
return bitStampTick.json()['last']
def btstampVWAP():
bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/')
return bitStampTick.json()['vwap']
def btstampHigh():
bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/')
return bitStampTick.json()['high']
def btstampLow():
bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/')
return bitStampTick.json()['low']
def btstampOpen():
bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/')
return bitStampTick.json()['open']
def btstampVol():
bitStampTick = requests.get('https://www.bitstamp.net/api/ticker/')
return bitStampTick.json()['volume']
while True:
timestamp = btstampTime()
last = float(btstampLast())
vwap = float(btstampVWAP())
high = float(btstampHigh())
low = float(btstampLow())
open = float(btstampOpen())
vol = float(btstampVol())
writer.writerow({'time': timestamp,
'last': last,
'vwap': vwap,
'high': high,
'low': low,
'open': open,
'vol': vol})
print('Time: ', timestamp)
print('Last =', last)
print('VWAP =', vwap)
print('High =', high)
print('Low =', low)
print('Open =', open)
print('Volume =', vol)
print('')
time.sleep(60)
答案 0 :(得分:2)
这是工作(和优化:))解决方案。请记住,信息将写入文件,但操作系统可能无法实时直观地更新文件大小。
import os
import csv
import time
import requests
csv_file = open('data.csv', 'w')
field_names = ['time', 'last', 'vwap', 'high', 'low', 'open', 'vol']
writer = csv.DictWriter(csv_file, fieldnames=field_names)
writer.writeheader()
while True:
info = requests.get('https://www.bitstamp.net/api/ticker/').json()
writer.writerow({'time': info['timestamp'],
'last': info['last'],
'vwap': info['vwap'],
'high': info['high'],
'low' : info['low'],
'open': info['open'],
'vol' : info['volume']})
csv_file.flush()
os.fsync(csv_file.fileno())
time.sleep(60)
# this line is optional, you can delete it.
print('Info appended.')
答案 1 :(得分:0)
使用pandas:
timestamp,last,vwap,high,low,open,volume
1521332251,7831.18,8069.97,8356.40000000,7730.23000000,7860.83,11882.59781852
使用:
创建ouput.csv{{1}}