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

火山引擎 最新活动