【问题标题】:csv header in python only on the top row?python中的csv标头仅在第一行?
【发布时间】:2021-06-12 14:38:11
【问题描述】:

我编写了一个 python 程序,它每分钟对网络服务器进行一次 api 调用,然后解析 json 响应并将解析后的值保存到 csv 文件中。

这是将值保存到 csv 文件中的代码:

with open('data.csv', 'a', newline='') as file:
    writer = csv.writer(file)
    writer.writerow([current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])

我怎样才能让它只在最上面一行而不是每一行保存一次标题?

更新:

这里有更多代码来调用 api 并将数据写入文件:

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
import requests
import json
import csv
from datetime import datetime






def fn():
    print("Starting...")
    session_id = "auZsJ4F2RsQNJxSPTMDt2238324"
    Outlook='http://www.myfxbook.com/api/get-community-outlook.json?session=' + session_id
    Outlook_response = requests.get(Outlook)
    Outlook_data = Outlook_response.json()['symbols']
    now = datetime.now()
    current_time = now.strftime("%H:%M")





    EURUSD=Outlook_data[0]
    SHORTPERC=EURUSD['shortPercentage']
    LONGPERC =EURUSD['longPercentage']
    SHORTvolume=EURUSD['shortVolume']
    longVolume=EURUSD['longVolume']
    longPositions=EURUSD['longPositions']
    shortPositions=EURUSD['shortPositions']
    with open('data.csv', 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])
    with open('data1.csv', 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([SHORTvolume, longVolume])
    with open('data2.csv', 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow([SHORTPERC, LONGPERC])

我不能发布完整的代码,因为它有大约 700 行长,会非常难看,但是上面提到的代码应该可以创建 csv 文件

这是我的一个 csv 文件的外观:

07:11,31,69,555.55,1265.14,4750,2607
07:12,31,69,555.55,1265.16,4751,2607
07:13,31,69,555.55,1265.16,4751,2607
07:14,30,70,555.56,1267.36,4752,2608
07:15,30,70,555.56,1267.36,4752,2608
07:16,30,70,555.56,1267.36,4752,2608
07:17,30,70,555.46,1267.36,4752,2607
07:18,31,69,558.61,1267.36,4752,2610
07:19,31,69,558.61,1267.37,4753,2610
07:20,31,69,561.58,1267.37,4753,2611
07:21,31,69,561.61,1267.37,4753,2613
07:22,31,69,561.65,1267.37,4753,2614
07:23,31,69,561.65,1267.36,4752,2614

这只是 csv 文件的一部分,随着时间的推移,更多的行会不断增加

编辑 2: Sparkofska 建议的答案似乎有效,但不知何故,它最终在每一行之间给出了一个空行,如下所示:

时间,ShortPer,LongPer,ShortVolume,LongVolume,ShortPosition,LongPosition

05:47,44,56,19528.8,24789.27,65223,48630

05:48,44,56,19529.04,24789.27,65223,48633

代码:

EURUSD=Outlook_data[0]
SHORTPERC=EURUSD['shortPercentage']
LONGPERC =EURUSD['longPercentage']
SHORTvolume=EURUSD['shortVolume']
longVolume=EURUSD['longVolume']
longPositions=EURUSD['longPositions']
shortPositions=EURUSD['shortPositions']
filename='EURUSD.csv';

def write_row_header_aware(filename, row):

     
    if not os.path.exists(filename) or os.stat(filename).st_size == 0:
         
        with open(filename, 'a') as file:
            writer = csv.writer(file)
            writer.writerow(['Time', 'ShortPer', 'LongPer','ShortVolume','LongVolume','ShortPosition','LongPosition'])

     
    with open(filename, 'a') as file:
        writer = csv.writer(file)
        writer.writerow([current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])
    
write_row_header_aware(filename, [current_time,SHORTPERC, LONGPERC, SHORTvolume, longVolume, longPositions, shortPositions])
print("done...")

【问题讨论】:

  • 我试过 sn-p,它只在文件中写了一行,没有标题。你能添加一个更广泛的例子吗?
  • 您的代码没有给出您所说的输出。可能会发布更多代码以及您获得的一小部分输出。
  • 我已经更新了代码并添加了更多代码
  • 查看DictWriter
  • 这能回答你的问题吗? Pythonically add header to a csv file

标签: python csv


【解决方案1】:

请检查文件是否存在,如果已经存在,请使用追加将行写入文件,否则写入标题。通过这种方式,您可以避免多次写入标题。请refer to this link

【讨论】:

    【解决方案2】:

    您可以包装writerow 函数,让它在需要时自动添加标题。

    如果您的输出 csv 文件不为空,我们可以断言标题已写入并简单地附加该行。否则(文件不存在或为空)我们在追加行之前写入标题。

    import os
    
    def write_row_header_aware(filename, row):
    
        # in case file doesn't exist or is empty
        if not os.path.exists(filename) or os.stat(filename).st_size == 0:
            # write header
            with open(filename, 'a', newline='') as file:
                writer = csv.writer(file)
                writer.writerow(['current_time', 'SHORTPERC', 'LONGPERC', ...])
    
        # write line as usual
        with open(filename, 'a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(row)
        
    write_row_header_aware('data.csv', [current_time, SHORTPERC, LONGPERC, ...])
    

    【讨论】:

    • 感谢@Sparkofska 解决方案似乎正在工作,但它在行之间产生空白,我已经编辑了显示问题的 OP,你能检查我是否做错了吗?
    • 这可能是由于 Windows 上的行终止符。尝试将newline='' 参数添加到open() 函数中,就像在第一个代码sn-p 中那样。请参阅我编辑的答案。
    • 是的,添加 newline=' ' 就像一个魅力
    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 2021-11-28
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多