You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现每秒刷新API数据导出的CSV文件内容?

How to Refresh CSV Export Every Second in Python

Hey there! I see you want to make your Kraken trade data CSV update every second instead of just once. Let's tweak your code to make that happen—here's a robust solution with clear explanations:

First, we'll use an infinite loop to repeat the data fetch/write process, add a 1-second delay between iterations, and use safe file handling to avoid unexpected issues. Here's the modified code:

import requests
import csv
import time

while True:
    try:
        # Grab the latest trade data from Kraken's API
        api_response = requests.get('https://api.kraken.com/0/public/Trades?pair=XBTUSD').json()
        
        # Write data to CSV (overwrites the file each time for fresh content)
        with open("order_book.csv", "w", newline='') as csv_file:
            writer = csv.writer(csv_file, lineterminator='\n')
            for trade in api_response['result']['XXBTZUSD']:
                writer.writerow(trade)
        
        print("CSV refreshed successfully!")
        time.sleep(1)  # Pause for 1 second before next refresh
    except Exception as error:
        # Handle any issues (like network drops or API errors) without crashing
        print(f"Oops, something went wrong: {error}")
        time.sleep(1)  # Still wait a second before retrying

Key Changes Explained:

  • Infinite while True Loop: This keeps the code running indefinitely, repeating the data fetch and write steps over and over.
  • with Statement for File Handling: This automatically closes the CSV file after writing, which prevents resource leaks and ensures the file is properly saved before the next iteration.
  • time.sleep(1): Adds a 1-second pause between each cycle, so your CSV updates exactly once per second.
  • Error Handling: The try-except block catches common issues like network failures or unexpected API responses, so your script won't crash immediately—it'll just log the error and keep trying.

A quick note: I renamed the output file to order_book.csv (added the .csv extension) to make it easier to open with spreadsheet tools, but you can switch back to your original filename if you prefer.

内容的提问来源于stack exchange,提问作者Rasbid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:02:44