You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python预算应用SQLite导出CSV无内容问题排查求助

Troubleshooting & Fixing Your Budget App's CSV Export Issue

Let's walk through the problems in your code step by step and get that CSV export working properly:

Key Issues Identified

  1. Mismatched & Unused Function Parameters
    Your backend summarize_of_total_expenses function defines 4 parameters (ExpensesName, Amount, WhichAccount, Timestamp) but never uses them, and your frontend calls the function without passing any arguments. This creates unnecessary confusion and could lead to silent failures.

  2. Cursor Reference Error
    You assign self.curs = conn.cursor() but then try to fetch data with curs.fetchall() (missing the self. prefix). This means you're trying to access an undefined local variable, resulting in no data being retrieved.

  3. Incorrect Data Type Handling
    SQLite's fetchall() returns a list of tuples, not dictionaries. Trying to call .keys() on a tuple will either throw an error or (if the result is empty) fail silently—explaining your blank CSV.

  4. Wrong File Mode for CSV Writing
    Using "wb" (binary write) mode in Python 3 breaks the csv module, which expects text mode. You also need to set newline='' to avoid extra blank lines in the CSV.

  5. Frontend List Insertion Missing Data
    Your frontend calls list1.insert(END) without passing any data, so even if the backend works, your UI won't show results.


Fixed Code Snippets

Backend Code

import csv  # Make sure this import is at the top of your file

def summarize_of_total_expenses(self):  # Remove unused parameters
    self.curs = conn.cursor()
    self.curs.execute("select * from book")
    
    # Get column names from the cursor description
    column_names = [desc[0] for desc in self.curs.description]
    # Convert tuple rows to dictionaries (matches column names to values)
    rows = self.curs.fetchall()
    expense_records = [dict(zip(column_names, row)) for row in rows]
    
    # Write to CSV correctly
    with open("mycsvfile.csv", "w", newline='', encoding='utf-8') as f:
        if expense_records:  # Only write if there's data to export
            writer = csv.DictWriter(f, fieldnames=column_names)
            writer.writeheader()  # Writes column names as the first row
            writer.writerows(expense_records)
    
    self.curs.close()
    return expense_records  # Return data to frontend for UI display

Frontend Code

def summarize_of_total_expenses_command():  # Frontend
    list1.delete(0, END)
    # Fetch data from backend and populate the list
    expense_data = database.summarize_of_total_expenses()
    for record in expense_data:
        # Customize the display format to match your app's needs
        list_item = f"{record['Timestamp']} | {record['ExpensesName']} | ${record['Amount']} | {record['WhichAccount']}"
        list1.insert(END, list_item)

Additional Checks

  • Verify your book table actually contains data: Run select * from book in a SQLite browser to confirm records exist.
  • Ensure your database connection (conn) is properly initialized before calling this function.

内容的提问来源于stack exchange,提问作者Hawkeye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:46:40