CSV不断覆盖

2024-10-01 07:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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()

Tags: csvtextimport程序getascolumnexport
2条回答

根据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'是始终写入文件末尾的正确模式

尝试使用“a”而不是“w”,并告知发生的情况。 “w”仅用于写入,光标不会移动到文件的末尾,因此它会覆盖

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

相关问题 更多 >