Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a row at top of CSV file in Python

Tags:

python

csv

I would like to append a row to the top of my csv file using python. I have 4 columns I need to add to. So far this is what I have for the code:

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

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

There are two things wrong with this though: I get an error saying "Expected a character buffer object" which I am sure has something to do with my variable "rows".

The second issue is that I believe this would only append it to the bottom, whereas I would need it at the top.

Any help would be appreciated.

like image 933
Will B Avatar asked Dec 21 '25 23:12

Will B


2 Answers

You seem to have two issues here:

  1. You get an error saying "Expected a character buffer object".

    This is because you can only write strings or character arrays to files, whereas a tuple is neither of these things (even if it is a tuple of strings or characters). You must first convert your tuple to a string. One simple way is to use str(('A', 'B', 'C', 'D')) or repr(('A', 'B', 'C', 'D')). If this does not work for you, it would then be better to extract each component and form a single string from it, say with

    a = ''
    for c in ('A', 'B', 'C', 'D'):
        a += c + ' '
    
  2. You want to append to the top of a text file rather than the bottom. Unfortunately you cannot do this simply. See here for a full description. The way around this is to read in your entire file as a string, insert your desired text to the beginning of this, then rewrite it all to a file.

like image 60
zephyr Avatar answered Dec 23 '25 11:12

zephyr


It is a bit overkill for something this simple but I find it quite helpful to have a class that handles some spread sheet like operations. Here is a simple one oriented around independent rows.

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"))

yielding

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

To address the problem you are having notice that the prt method returns a string not a list allowing it to be passed to the file.write() method.

like image 20
kpie Avatar answered Dec 23 '25 11:12

kpie