Python预算应用SQLite导出CSV无内容问题排查求助
Let's walk through the problems in your code step by step and get that CSV export working properly:
Key Issues Identified
Mismatched & Unused Function Parameters
Your backendsummarize_of_total_expensesfunction 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.Cursor Reference Error
You assignself.curs = conn.cursor()but then try to fetch data withcurs.fetchall()(missing theself.prefix). This means you're trying to access an undefined local variable, resulting in no data being retrieved.Incorrect Data Type Handling
SQLite'sfetchall()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.Wrong File Mode for CSV Writing
Using"wb"(binary write) mode in Python 3 breaks thecsvmodule, which expects text mode. You also need to setnewline=''to avoid extra blank lines in the CSV.Frontend List Insertion Missing Data
Your frontend callslist1.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
booktable actually contains data: Runselect * from bookin a SQLite browser to confirm records exist. - Ensure your database connection (
conn) is properly initialized before calling this function.
内容的提问来源于stack exchange,提问作者Hawkeye

