簡體   English   中英

在 Python 中的 CSV 文件頂部插入一行

[英]Insert a row at top of CSV file in Python

我想使用 python 在我的 csv 文件的頂部追加一行。 我有 4 列需要添加。 到目前為止,這是我的代碼:

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

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

但是,這有兩個問題:我收到一條錯誤消息,說“預期是字符緩沖區對象”,我確信這與我的變量“行”有關。

第二個問題是我相信這只會將它附加到底部,而我需要它在頂部。

任何幫助,將不勝感激。

你這里似乎有兩個問題:

  1. 您收到一條錯誤消息,提示“需要字符緩沖區對象”。

    這是因為您只能將字符串或字符數組寫入文件,而元組不是這些東西(即使它是字符串或字符的元組)。 您必須首先將元組轉換為字符串。 一種簡單的方法是使用str(('A', 'B', 'C', 'D'))repr(('A', 'B', 'C', 'D')) 如果這對您不起作用,那么最好提取每個組件並從中形成一個字符串,例如

    a = '' for c in ('A', 'B', 'C', 'D'): a += c + ' '
  2. 您想附加到文本文件的頂部而不是底部。 不幸的是,您不能簡單地做到這一點。 有關完整說明,請參見此處 解決這個問題的方法是將整個文件作為一個字符串讀入,將所需的文本插入到它的開頭,然后將其全部重寫到一個文件中。

對於這么簡單的事情來說有點矯枉過正,但我​​發現擁有一個處理諸如操作之類的電子表格的類非常有幫助。 這是一個圍繞獨立行的簡單方法。

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() 在文件開頭?

我不是一個有經驗的程序員,但我在頂部添加行的邏輯是這樣的:

  1. 對 CSV 數據進行排序並將其倒置(我認為 Pandas 具有排序功能)

    您可能需要添加一個數字為 0-n 的列(我的意思是序列號),然后您可以根據降序對數據進行排序。

  2. 然后追加行 >> 你知道它將被追加到底部。

  3. 按照遞增的數字再次排序。

  4. 現在刪除您添加的列。

這樣,您底部的數據將到達頂部!

我希望這有幫助。

你可以試試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM