python - 只写一次特定行?
问题描述
我想在 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']
在文件顶部只写一次,而不是每两行。
解决方案
这是因为您以附加模式 ( '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)
推荐阅读
- python - TkInter:两个按钮之间的传输变量
- javascript - 如何将 json 瓦片集(从瓦片地图编辑器)渲染到画布 javascript
- sql - SQL 根据 from 和 to 日期查询出生日期和月份
- ffmpeg - 使用 FFMPEG 将帧添加到 gif
- regex - 在 vscode 中查找双破折号
- python - 将 pandas 或 keras 中的样本数据自动上调或下调至统一大小的简单方法
- arm - Cortex-A57 是否有 CPU 周期计数功能
- asynchronous - 为什么我的异步请求比同步请求慢?
- django - 在 HTML 模板中输出音频流,django
- python - Serverless GCP Function 部署