简体   繁体   English

Header 写为 CSV Python 中的行

[英]Header written as row in CSV Python

I have the following code which I am using to create and add a new row to a csv file.我有以下代码用于创建新行并将其添加到 csv 文件。

def calcPrice(data):


   fieldnames = ["ReferenceID","clientName","Date","From","To","Rate","Price"]
   with open('rec2.csv', 'a') as csvfile:

     writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
     writer.writeheader()
     writer.writerow(data)

return However, it as the header as a new row as well. return 但是,它作为 header 作为新行也是如此。 How can I prevent this?我怎样才能防止这种情况? 在此处输入图像描述

Here's a link to the gist with the whole code: https://gist.github.com/chriskinyua/5ff8a527b31451ddc7d7cf157c719bba以下是整个代码的要点链接: https://gist.github.com/chriskinyua/5ff8a527b31451ddc7d7cf157c719bba

You could check if the file already exists您可以检查文件是否已存在

import os

def calcPrice(data):

   filename = 'rec2.csv'
   write_header = not os.path.exists(filename)

   fieldnames = ["ReferenceID","clientName","Date","From","To","Rate","Price"]
   with open(filename, 'a') as csvfile:

     writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
     if write_header:
        writer.writeheader()
     writer.writerow(data)

Let's assume there's a function we can call that will tell us whether we should write out the header or not, so the code would look like this:假设有一个我们可以调用的 function 会告诉我们是否应该写出 header,所以代码如下所示:

import csv

def calcPrice(data):

   fieldnames = ["ReferenceID","clientName","Date","From","To","Rate","Price"]
   with open('rec2.csv', 'a') as csvfile:

       writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
       if should_write_header(csvfile):
           writer.writeheader()
       writer.writerow(data)

What will should_write_header look like? should_write_header会是什么样子? Here are three possibilities.这里有三种可能性。 For all of them, we will need to import the io module:对于所有这些,我们需要导入io模块:

import io

The logic of all these functions is the same: we want to work out if the end of the file is the same as the beginning of the file.所有这些函数的逻辑都是一样的:我们要计算文件的结尾是否与文件的开头相同。 If that is true, then we want to write the header row.如果这是真的,那么我们要写入 header 行。

This function is the most verbose: it finds the current position using the file's tell method, moves to the beginning of the file using its seek method, then runs tell again to see if the reported positions are the same.这个 function 是最详细的:它使用文件的tell方法找到当前的 position,使用它的seek方法移动到文件的开头,然后再次运行tell以查看报告的位置是否相同。 If they are not it seek s back to the end of the file before returning the result.如果不是,它seek在返回结果之前返回文件末尾。 We don't simply compare the value of EOF to zero because the Python docs state that the result of tell for text files does not necessarily correspond to the actual position of the file pointer.我们不会简单地将EOF的值与零进行比较,因为 Python 文档 state tell文本文件的结果不一定对应于文件指针的实际 position。

def should_write_header1(fileobj):
    EOF = fileobj.tell()
    fileobj.seek(0, io.SEEK_SET)
    res = fileobj.tell() == EOF
    if not res:
        fileobj.seek(EOF, io.SEEK_SET)
    return res

This version assumes that while the tell method does not necessarily correspond to the position of the file pointer in general, tell will always return zero for an empty file.这个版本假定虽然tell方法通常不一定对应于文件指针的position,但是对于空文件, tell总是返回零。 This will probably work in common cases.这可能适用于常见情况。

def should_write_header2(fileobj):
    return fileobj.tell() == 0

This version accesses the tell method of the binary stream that TextIOWrapper (the text file object class) wraps.此版本访问TextIOWrapper (文本文件 object 类)包装的二进制 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 的tell方法。 For binary streams, tell is documented to return the actual file pointer position.对于二进制流, tell被记录为返回实际的文件指针 position。 This is removes the uncertainty of should_write_header2 , but unfortunately buffer is not guaranteed to exist in all Python implementations, so this isn't portable.这消除了should_write_header2的不确定性,但不幸的是, 缓冲区不能保证存在于所有 Python 实现中,所以这不是可移植的。

def should_write_header3(fileobj):
    return fileobj.buffer.tell() == 0

So for 100% certainty, use should_write_header1 .因此,为了 100% 的确定性,请使用should_write_header1 For less certainty but shorter code, use one of the others.对于不太确定但更短的代码,请使用其他代码之一。 If performance is a concern favour should_write_header3 , because tell in binary streams is faster than tell in text streams.如果性能是一个问题,那么应该关注should_write_header3 ,因为二进制流中的tell比文本流中的tell更快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM