在Python的CSV文件顶部插入一行

2024-06-06 20:56:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python在csv文件的顶部追加一行。我有4列需要添加。到目前为止,这就是我的代码:

rows= ('A','B','C','D')

fd = open('file.csv','a')
fd.write(rows)
fd.close()

但是有两个错误:我得到了一个错误,说“需要一个字符缓冲区对象”,我确信这与我的变量“rows”有关。

第二个问题是,我认为这只会将它附加到底部,而我需要它在顶部。

任何帮助都将不胜感激。


Tags: 文件csv对象代码close错误open字符
3条回答

对于这样简单的事情来说有点过分了,但是我发现有一个处理类似于电子表格的操作的类非常有帮助。这是一个简单的面向独立行的例子。

class Table():
    def __init__(self):# instanciates an empty table
        self.rows = []
    def push(self,row): # adds a row to the top of the table
        self.rows = [row]+self.rows
    def que(self,row): #adds a row to the bottom of the table
        self.rows = self.rows+[row]
    def remRowAt(self,i): # Removes a row from the table at a given index
        if(i>=0 and i<len(self.rows)):
            self.rows=self.rows[0:i]+self.rows[i+1:len(self.rows)]
        else:print("index error removing at:"+str(i))
    def addRowAt(self,i,row): #Adds a row at a given index
        if(i>=0 and i<= len(self.rows)):
            self.rows = self.rows[0:i]+[row]+self.rows[i:len(self.rows)]
        else:print("index error adding at:"+str(i))
    def prt(self,delim): # returns the table in the form of a string.
        s =""
        for row in self.rows:
            for entry in row:
                s+= str(entry)+delim
            s=s[0:len(s)-1]+"\n"
        s=s[0:len(s)-1]
        return(s)
    def read(self,s,delim):
        for k in s.split("\n"):
            self.que(k.split(delim))

t = Table()
t.push(['a','b','c','d'])
t.push([1,2,3,4])
t.que(['check','my','work'])
t.remRowAt(1)
t.addRowAt(2,[2,3,4,5])
print(t.prt(","))
copyT = Table()
copyT.read(t.prt(","),',')
print(">")
print(copyT.prt("\t"))

屈服

1,2,3,4
check,my,work
2,3,4,5
>
1   2   3   4
check   my  work
2   3   4   5

为了解决这个问题,您注意到prt方法返回一个字符串,而不是一个允许将其传递给file.write()方法的列表。

为什么会出错?

当需要"character buffer object"时,您正在将元组传递给write。实际上这意味着它需要一根绳子。

我建议使用pythoncsv.writer类来帮助您。 https://docs.python.org/2/library/csv.html#csv.writer

写入文件顶部。

也许这个答案有帮助:

Python f.write() at beginning of file?

你似乎有两个问题:

  1. 你得到一个错误说“需要一个字符缓冲区对象”。

    这是因为您只能将字符串或字符数组写入文件,而元组两者都不是(即使它是字符串或字符的元组)。必须先将元组转换为字符串。一个简单的方法是使用str(('A', 'B', 'C', 'D'))repr(('A', 'B', 'C', 'D'))。如果这对您不起作用,那么最好提取每个组件并从中形成一个字符串,例如

    a = ''
    for c in ('A', 'B', 'C', 'D'):
        a += c + ' '
    
  2. 您希望追加到文本文件的顶部,而不是底部。不幸的是你不能这么简单。有关详细说明,请参见here。解决这个问题的方法是将整个文件作为一个字符串读取,将所需的文本插入文件的开头,然后将其全部重写为一个文件。

相关问题 更多 >