【问题标题】:CSV keeps overwritingCSV 不断覆盖
【发布时间】:2020-08-24 12:57:15
【问题描述】:

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    尝试“a”而不是“w”并告知会发生什么。 'w' 仅用于写入,光标不会移动到文件末尾,所以它会覆盖

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-10
      • 2015-02-08
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2013-03-15
      • 2017-04-12
      相关资源
      最近更新 更多