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
。实际上这意味着它需要一根绳子。我建议使用python
csv.writer
类来帮助您。 https://docs.python.org/2/library/csv.html#csv.writer写入文件顶部。
也许这个答案有帮助:
Python f.write() at beginning of file?
你似乎有两个问题:
你得到一个错误说“需要一个字符缓冲区对象”。
这是因为您只能将字符串或字符数组写入文件,而元组两者都不是(即使它是字符串或字符的元组)。必须先将元组转换为字符串。一个简单的方法是使用
str(('A', 'B', 'C', 'D'))
或repr(('A', 'B', 'C', 'D'))
。如果这对您不起作用,那么最好提取每个组件并从中形成一个字符串,例如您希望追加到文本文件的顶部,而不是底部。不幸的是你不能这么简单。有关详细说明,请参见here。解决这个问题的方法是将整个文件作为一个字符串读取,将所需的文本插入文件的开头,然后将其全部重写为一个文件。
相关问题 更多 >
编程相关推荐