gpt4 book ai didi

Python:无法保存到 CSV

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:24 25 4
gpt4 key购买 nike

我有一个从 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)

最佳答案

这是有效的(和优化的 :))解决方案。请记住,信息将写入文件,但操作系统可能不会实时更新文件大小。

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.')

关于Python:无法保存到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49342838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com