简体   繁体   English

将多行写入 CSV

[英]Write multiple rows to a CSV

I have a small GUI which should write the values into a CSV file.我有一个小型 GUI,它应该将值写入 CSV 文件。 However, the header is always written instead of just the new entries.但是,始终写入 header 而不仅仅是新条目。

this is how it looks in the csv:这是它在 csv 中的样子:

Amount, Time
1000,12:13:40
Amount, Time
2000,12:14:30

What I want:我想要的是:

Amount, Time
1000,12:13:40
2000,12:14:30
def submit():
     import csv
     import datetime
     with open("Data_amount.csv", "a", newline="") as csvfile:
         writer = csv.writer(csvfile)
         #Header 
         writer.writerow(["Amount", "Time"])
         #Input
         input_amount = entry_listbox.get()
         #Time
         now = datetime.datetime.now()
         now_str = now.time().strftime("%H:%M:%S")
         writer.writerow([input_amount, now_str])

     timestamp = datetime.datetime.now()
     input_amount2 = entry_listbox.get() 

     if input_amount2 != "":
         listbox_stuekzahlen.insert(tkinter.END, f'{timestamp:%H:%M:%S} - {input_amount2} Stk.')
         entry_listbox.delete(0,tkinter.END)
     else:
        tkinter.messagebox.showwarning(title="Warning!", message="INPUT!")

You unconditionally write the header again each time you call submit .每次调用submit时,您无条件地再次写入 header。 Either:任何一个:

  1. Remove that header write, and have, somewhere outside submit (early in your program, run exactly once), the code that initializes (opens in "w" mode so the file is cleared) the file with just the header, so each submit doesn't add an extra copy, or删除 header 写入,并在submit之外的某个地方(在程序的早期,只运行一次)初始化代码(以"w"模式打开以便清除文件)只有 header 的文件,因此每次submit都不会' 添加一个额外的副本,或者

  2. Leave the header write it, but make it conditional on the file being empty (so you only write it when the file is already empty, and otherwise assume the file already has the header), eg保留 header 写入它,但以文件为空为条件(因此您只在文件已经为空时写入它,否则假设文件已经有标题),例如

     with open("Data_amount.csv", "a", newline="") as csvfile: writer = csv.writer(csvfile) #Header if not os.fstat(csvfile.fileno()).st_size: writer.writerow(["Amount", "Time"]) # Write header only if input is empty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM