简体   繁体   English

Python CSV模块的writerow方法跳过一行

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

I am working on a software to handle a firm's deadlines.我正在开发一种软件来处理公司的最后期限。 I want to export the SQL table to a CSV of excel file.我想将 SQL 表导出到 excel 文件的 CSV。 I have read this question How to export Mysql Table data to excel file using python script?我读过这个问题How to export Mysql Table data to excel file using python script? and tried the offered solution but I encountered an issue.并尝试了提供的解决方案,但我遇到了问题。 The CSV file skips a row (there is a blank line between each written line, see example). 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

The code is the following:代码如下:

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)

To simplify everyone's life I will simply attach the result of printing the result variable here (So that we don't need to work with the SQL tables.)为了简化每个人的生活,我将在这里简单地附上打印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}]

Following @Adrian Klaver comment's idea the issue may reside in the asksaveasfile function. If I print the file_path variable I get: name='C:/Users/serax/OneDrive/Documenti/a.csv' mode='w' encoding='cp1252'> .按照@Adrian Klaver 评论的想法,问题可能存在于asksaveasfile function 中。如果我打印 file_path 变量,我得到: name='C:/Users/serax/OneDrive/Documenti/a.csv' mode='w' encoding='cp1252'>

This is an io.TextIoWrapper ( https://docs.python.org/3/library/io.html#io.TextIOWrapper ) with some weird encoding in write mode.这是一个io.TextIoWrapper ( https://docs.python.org/3/library/io.html#io.TextIOWrapper ) 在写入模式下有一些奇怪的编码。 If i manage to retrieve the path of the file from this io.TextIoWrapper object I can then open it with the standard open() function and hopefully it will work.如果我设法从这个io.TextIoWrapper object 中检索文件的路径,然后我可以使用标准open() function 打开它,希望它能工作。

Any help is very much appreciated;!!很感谢任何形式的帮助;!! ;) ;)

SOLVED IT: :D解决了它::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)

Instead of using asksavefile which return an Io object I use asksavefilename which returns the path of the newly created file.我没有使用返回Io object 的asksavefile ,而是使用返回新创建文件路径的asksavefilename Then I just open it normally and add the newline="" to open() .然后我只是正常打开它并将newline=""添加到open() The file now does not leave any blank line!该文件现在不留任何空行!

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

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