【问题标题】:Insert a row at top of CSV file in Python在 Python 中的 CSV 文件顶部插入一行
【发布时间】:2015-04-19 22:54:17
【问题描述】:

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

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

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

这有两个问题:我收到一条错误消息,提示“需要一个字符缓冲区对象”,我确信这与我的变量“rows”有关。

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

任何帮助将不胜感激。

【问题讨论】:

标签: python csv


【解决方案1】:

你这里似乎有两个问题:

  1. 您收到一条错误消息,提示“需要一个字符缓冲区对象”。

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

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

【讨论】:

    【解决方案2】:

    对于这么简单的事情来说有点矫枉过正,但我​​发现拥有一个处理类似电子表格的操作的类非常有帮助。这是一个围绕独立行的简单方法。

    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() 方法的列表。

    【讨论】:

      【解决方案3】:

      为什么会出错?

      当需要 "character buffer object" 时,您将元组传递给 write。实际上,这意味着它需要一个字符串。

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

      写入文件顶部。

      也许这个答案有帮助:

      Python f.write() at beginning of file?

      【讨论】:

        【解决方案4】:

        我不是经验丰富的程序员,但我在顶部添加行的逻辑是这样的:

        1. 对 CSV 数据进行排序并使其倒置(我认为 Pandas 有排序功能)

          您可能需要添加一个数字为 0-n(我的意思是序列号)的列,然后您可以按降序对数据进行排序。

        2. 然后追加行>>你知道它会追加到底部。

        3. 按照增加的数量重新排序。

        4. 现在删除您添加的列。

        这样你底部的数据就会到达顶部!

        我希望这会有所帮助。

        【讨论】:

          【解决方案5】:

          你可以试试这个:

          import csv
          
          row = ['A','B','C','D']
          
          with open(filename, 'r') as readFile:
              rd = csv.reader(readFile)
              lines = list(rd)
              lines.insert(0, row)
          
          with open(filename, 'w',newline='') as writeFile:
              wt = csv.writer(writeFile)
              wt.writerows(lines)
          
          readFile.close()
          writeFile.close()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-06-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多