首页 > 解决方案 > 只写一次特定行?

问题描述

我想在 CSV 文件中写入一些数据。我这样做没有问题。我得到的唯一问题是我只想写一次“标题”,但它每两行写一次。

这是我的代码:

rows = [['IVE_PATH','FPS moyen','FPS max','FPS min','MEDIAN'],[str(listFps[k]),statistics.mean(numberList), max(numberList), min(numberList), statistics.median(numberList)]]

with open("C:\ProgramData\OutilTestObjets3D\MaquetteCB-2019\DataSet\doc.csv", 'a', newline='') as csvfile:
    csv_writer = csv.writer(csvfile, delimiter=';')
    for row in rows:
        csv_writer.writerow(row)
k += 1

我想要这个:

['IVE_PATH','FPS moyen','FPS max','FPS min','MEDIAN']

在文件顶部只写一次,而不是每两行。

标签: pythoncsvrow

解决方案


这是因为您以附加模式 ( 'a')打开文件,并且rows 每次写入文件时都在迭代。这意味着每次写入时,都会将标题和数据添加到现有文件中。

解决方案是将表头和数据行的写入分开。

一种方法是首先检查您是否正在使用tell()写入一个空文件,如果是,那么这是写入标题的唯一时间。然后继续迭代标题之外的所有行。

import csv

rows = [
    ['IVE_PATH','FPS moyen','FPS max','FPS min','MEDIAN'],  # header
    [1,2,3,4,5],                                            # sample data
    [6,7,8,9,0]                                             # sample data
]

with open("doc.csv", 'a', newline='') as csvfile:
    csv_writer = csv.writer(csvfile, delimiter=';')

    # Check if we are at the top of an empty file.
    # If yes, then write the header.
    # If no, then assume that the header was already written earlier.
    if csvfile.tell() == 0:
        csv_writer.writerow(rows[0])

    # Iterate over only the data, skip rows[0]
    for row in rows[1:]:
        csv_writer.writerow(row)

另一种方法是首先检查输出 CSV 文件是否存在。如果它尚不存在,请创建它并写入标题行。然后您的代码的后续运行应该只附加数据行。

import csv
import os

rows = [
    ['IVE_PATH','FPS moyen','FPS max','FPS min','MEDIAN'],  # header
    [1,2,3,4,5],                                            # sample data
    [6,7,8,9,0]                                             # sample data
]

csvpath = "doc.csv"

# If the output file does not exist yet, create it.
# Then write the header row.
if not os.path.exists(csvpath):
    with open(csvpath, "w") as csvfile:
        csv_writer = csv.writer(csvfile, delimiter=';')
        csv_writer.writerow(rows[0])

with open(csvpath, 'a', newline='') as csvfile:
    csv_writer = csv.writer(csvfile, delimiter=';')

    # Iterate over only the data, skip rows[0]
    for row in rows[1:]:
        csv_writer.writerow(row)

推荐阅读