[英]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.我想使用 python 在我的 csv 文件的顶部追加一行。 I have 4 columns I need to add to.我有 4 列需要添加。 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:你这里似乎有两个问题:
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'))
.一种简单的方法是使用str(('A', 'B', 'C', 'D'))
或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 + ' '
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.为了解决这个问题,您注意到 prt 方法返回一个字符串而不是一个列表,允许将其传递给 file.write() 方法。
Why the error?为什么会出错?
You are passing a tuple to write
when a "character buffer object"
is expected.当需要"character buffer object"
时,您正在传递一个要write
的元组。 In reality this means it wants a string.实际上,这意味着它需要一个字符串。
I suggest using the python csv.writer
class to help you.我建议使用 python csv.writer
类来帮助你。 https://docs.python.org/2/library/csv.html#csv.writer 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? Python f.write() 在文件开头?
I am not an experienced programmer but my logic to add the row at top is like this:我不是一个有经验的程序员,但我在顶部添加行的逻辑是这样的:
Sort CSV data and make it upside down (I think Pandas has sorting features)对 CSV 数据进行排序并将其倒置(我认为 Pandas 具有排序功能)
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.您可能需要添加一个数字为 0-n 的列(我的意思是序列号),然后您可以根据降序对数据进行排序。
Then append row >> you know that it will be appended at the bottom.然后追加行 >> 你知道它将被追加到底部。
Sort again according to increasing number.按照递增的数字再次排序。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.