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.