CSV不断覆盖

问题描述 投票:0回答:2

我正在尝试使用Python为我的父母制作一个快速的簿记程序。我希望它如何工作如下。每次父母打开此程序时,我都希望它在excel文件中添加新行。问题在于,每次程序运行时,它都会覆盖自身。在下面,您会看到我的代码

from tkinter import *
import csv
import pandas as pd

root = Tk()
root.title('Boekhouding 2020')
root.minsize(250, 100)
#Weeknummer
Label1 = Label(root, text= "Weeknummer").grid(row=1, column=1)
e1 = Entry(root)
e1.grid(row=1, column=2)
#Omschrijving
Label2 = Label(root, text= "Omschrijving").grid(row=2, column=1)
e2 = Entry(root)
e2.grid(row=2, column=2)
#Bedrag
Label3 = Label(root, text= "Bedrag").grid(row=3, column=1)
e3 = Entry(root)
e3.grid(row=3, column=2)



##  Exporteren naar Excel
def export(oms,bedrag,weeknummer):
    with open(r"C:\Users\frank\Desktop\Boekhouding.csv", 'w', newline='') as f:
        thewriter = csv.writer(f)
        row_export()
        thewriter.writerow([oms,bedrag,weeknummer])

## Klik definition
def myclick():
    mylabel = Label(root, text='Hello ' + e1.get())
    mylabel.grid(row=5, column=1)
    export(e2.get(),e3.get(),e1.get())

## Rowcounter
def row_export():
    with open(r"C:\Users\frank\Desktop\Boekhouding.csv",'r')as csv_file:
        fileObject = csv.reader(csv_file)
        for row in fileObject:
            print(row)
            export(row[0],row[1],row[2])



## All buttons
mybutton = Button(root, text="exporteren naar excel", command=myclick)
mybutton.grid(row=4, column=1)

root.mainloop()
python excel csv tkinter overwrite
2个回答
0
投票

尝试“ a”而不是“ w”,然后告知会发生什么。“ w”仅用于写入,并且光标不会移到文件末尾,因此它会覆盖

https://docs.python.org/3/library/functions.html#open


0
投票

摘自Python open的定义:

Character Meaning
   'r'    open for reading (default)
   'w'    open for writing, truncating the file first
   'x'    open for exclusive creation, failing if the file already exists
   'a'    open for writing, appending to the end of the file if it exists
   'b'    binary mode
   't'    text mode (default)
   '+'    open for updating (reading and writing)

使用正确的模式。 'w'始终以空文件开头。 'a'是始终写入文件末尾的正确模式。

© www.soinside.com 2019 - 2024. All rights reserved.