简体   繁体   中英

Insert a row at top of CSV file in Python

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.

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.

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.

Why the error?

You are passing a tuple to write when a "character buffer object" is expected. In reality this means it wants a string.

I suggest using the python csv.writer class to help you. https://docs.python.org/2/library/csv.html#csv.writer

Writing to the top of the file.

Perhaps this answer helps:

Python f.write() at beginning of file?

I am not an experienced programmer but my logic to add the row at top is like this:

  1. Sort CSV data and make it upside down (I think Pandas has sorting features)

    you might have to add a column with numbers 0- n (I mean serial number) and then you can sort data according to descending order.

  2. Then append row >> you know that it will be appended at the bottom.

  3. Sort again according to increasing number.

  4. Now delete the column that you have added.

This way your data at the bottom will reach at top!

I hope this helps.

You can try this one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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