簡體   English   中英

Python CSV模塊的writerow方法跳過一行

[英]Python writerow method from CSV module skips a line

我正在開發一種軟件來處理公司的最后期限。 我想將 SQL 表導出到 excel 文件的 CSV。 我讀過這個問題How to export Mysql Table data to excel file using python script? 並嘗試了提供的解決方案,但我遇到了問題。 CSV 文件跳過一行(每個寫入行之間有一個空行,請參見示例)。

rg,parti,oggetto,incombente,autorita,giudice,deadline_id,member_id,data,ora,minuti,notes,terminata

123,io,bo,a,ibi,prof,2,1,2022-11-13,10,0,adfggnadfnadf,0

123,io,bo,ia,ib,prof,3,1,2023-01-14,1,24,adfggnadfnadfadfggnadfnadf,0

1241426,sdfgn,ASDG,srtgnawetjn,hgdm,sry,4,1,2023-01-07,10,24,WQEGOUIB<IUSDBV,0

124512,wrtj,SADG,tgjw,rtyj,sfgjh,5,1,2023-01-07,10,31,srgoibn,0

代碼如下:

cursor.execute("SELECT * FROM `lawsuit` INNER JOIN `calendar` WHERE lawsuit.rg = calendar.rg;")
result = cursor.fetchall()
print(result)

        def save_file():
            file_path = asksaveasfile(initialfile='Untitled.csv',
                                      defaultextension=".csv",
                                      filetypes=[("CSV file", "*.csv")])
            if file_path:
                writer = csv.writer(file_path)
                writer.writerow(result[0].keys())
                for row in result:
                    print(row)
                    writer.writerow(row.values())
            else:
                messagebox.showerror("NO FILE SELECTED", "You have cancelled the action, the file has not been created")

btn = tk.Button(self.root, text="Export to CSV", command=lambda: save_file())
btn.place(x=10, y=10)

為了簡化每個人的生活,我將在這里簡單地附上打印result變量的結果(這樣我們就不需要使用 SQL 表了。)

[{'rg': 123, 'parti': 'io', 'oggetto': 'bo', 'incombente': 'a', 'autorita': 'ibi', 'giudice': 'prof', 'deadline_id': 2, 'member_id': 1, 'data': datetime.date(2022, 11, 13), 'ora': 10, 'minuti': 0, 'notes': 'adfggnadfnadf', 'terminata': 0}, {'rg': 123, 'parti': 'io', 'oggetto': 'bo', 'incombente': 'ia', 'autorita': 'ib', 'giudice': 'prof', 'deadline_id': 3, 'member_id': 1, 'data': datetime.date(2023, 1, 14), 'ora': 1, 'minuti': 24, 'notes': 'adfggnadfnadfadfggnadfnadf', 'terminata': 0}, {'rg': 1241426, 'parti': 'sdfgn', 'oggetto': 'ASDG', 'incombente': 'srtgnawetjn', 'autorita': 'hgdm', 'giudice': 'sry', 'deadline_id': 4, 'member_id': 1, 'data': datetime.date(2023, 1, 7), 'ora': 10, 'minuti': 24, 'notes': 'WQEGOUIB<IUSDBV', 'terminata': 0}, {'rg': 124512, 'parti': 'wrtj', 'oggetto': 'SADG', 'incombente': 'tgjw', 'autorita': 'rtyj', 'giudice': 'sfgjh', 'deadline_id': 5, 'member_id': 1, 'data': datetime.date(2023, 1, 7), 'ora': 10, 'minuti': 31, 'notes': 'srgoibn', 'terminata': 0}, {'rg': 12453425, 'parti': 'arhnadfn', 'oggetto': 'sdfna', 'incombente': 'aedrh', 'autorita': 'sdfgn', 'giudice': 'aetn', 'deadline_id': 6, 'member_id': 1, 'data': datetime.date(2023, 1, 7), 'ora': 10, 'minuti': 30, 'notes': 'enqefnadfn\naethnadf', 'terminata': 0}]

按照@Adrian Klaver 評論的想法,問題可能存在於asksaveasfile function 中。如果我打印 file_path 變量,我得到: name='C:/Users/serax/OneDrive/Documenti/a.csv' mode='w' encoding='cp1252'>

這是一個io.TextIoWrapper ( https://docs.python.org/3/library/io.html#io.TextIOWrapper ) 在寫入模式下有一些奇怪的編碼。 如果我設法從這個io.TextIoWrapper object 中檢索文件的路徑,然后我可以使用標准open() function 打開它,希望它能工作。

很感謝任何形式的幫助;!! ;)

解決了它::D

cursor.execute("SELECT * FROM `lawsuit` INNER JOIN `calendar` WHERE lawsuit.rg = calendar.rg;")
result = cursor.fetchall()
print(result)    
file_path = asksaveasfilename(initialfile='Untitled.csv',
                                          defaultextension=".csv",
                                          filetypes=[("CSV file", "*.csv")])
print(file_path)
if file_path:
      with open(file_path, "w", newline="") as file:
                    writer = csv.writer(file)
                    writer.writerow(result[0].keys())
                    for row in result:
                        print(row)
                        writer.writerow(row.values())
else:
     messagebox.showerror("NO FILE SELECTED", "You have cancelled the action, the file has not been created")

btn = tk.Button(self.root, text="Export to CSV", command=lambda: save_file())
btn.place(x=10, y=10)

我沒有使用返回Io object 的asksavefile ,而是使用返回新創建文件路徑的asksavefilename 然后我只是正常打開它並將newline=""添加到open() 該文件現在不留任何空行!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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