[Python] phyton extract csv from sqlite db [closed]

Discussão em 'Python' iniciado por Stack, Janeiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to export data from an SQLite database to a CSV file using Python, but the columns in the exported CSV file are shifted. I attempted to fix the issue by adjusting the column order in the code, but the problem persists. Here’s the code I’m working with:

    def export_csv_ste():
    try:
    # Assicurati che la cartella "Export" esista
    export_folder = "EXPORT"
    if not os.path.exists(export_folder):
    os.makedirs(export_folder)

    # Definisci il percorso completo del file CSV
    filename = os.path.join(export_folder, "export_ste.csv")

    # Connessione al database
    conn = connect_db()
    c = conn.cursor()

    # Esegui la query per ottenere i dati
    c.execute('SELECT * FROM prodotti')
    rows = c.fetchall()

    # Definisci le colonne come nel formato fornito
    column_headers = [
    "ID", "productid" ,"Active", "Name", "Categories", "Price tax excluded", "Tax rule", "Cost price", "On sale",
    "Discount amount", "Discount percent", "Discount from", "Discount to", "Reference", "Supplier reference",
    "Supplier", "Brand", "EAN-13", "UPC", "MPN", "Ecotax", "Width", "Height", "Depth", "Weight",
    "Delivery time of in-stock products", "Delivery time of out-of-stock products with allowed orders",
    "Quantity", "Minimal quantity", "Low stock level", "Receive a low stock alert by email", "Visibility",
    "Additional shipping cost", "Unit for base price", "Base price", "Summary", "Description", "Tags",
    "Meta title", "Meta keywords", "Meta description", "Rewritten URL", "Label when in stock",
    "Label when backorder allowed", "Available for order", "Product availability date", "Product creation date",
    "Show price", "Image URLs", "Image alt texts", "Delete existing images", "Feature", "Available online only",
    "Condition", "Customizable", "Uploadable files", "Text fields", "Action when out of stock",
    "Virtual product", "File URL", "Number of allowed downloads", "Expiration date", "Number of days",
    "ID / Name of the store", "Advanced stock management", "Depends on stock", "Warehouse", "Accessories"
    ]

    # Lista per contenere le righe modificate
    modified_rows = []

    # Applica la correzione alle righe
    for row in rows:
    row = list(row) # Converte la tupla in lista

    # Applica la riorganizzazione delle colonne
    corrected_row = row[:]
    corrected_row[6] = row[5] # Tax rule → Cost price
    corrected_row[5] = row[4] # Cost price → Price tax excluded
    corrected_row[4] = row[3] # Price tax excluded → Categories
    corrected_row[3] = row[2] # Categories → Name

    # Aggiungi la riga corretta alla lista
    modified_rows.append(corrected_row)

    # Scrivi i dati corretti nel CSV
    with open(filename, "w", newline="", encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile, delimiter=';') # Usa ";" come separatore
    writer.writerow(column_headers) # Scrivi l'intestazione delle colonne
    writer.writerows(modified_rows) # Scrivi i dati modificati

    # Chiudi la connessione al database
    conn.close()
    messagebox.showinfo("Successo", f"Dati esportati con successo in {filename}")
    except Exception as e:
    messagebox.showerror("Errore", f"Errore durante l'esportazione: {e}")


    my sqlite table

    CREATE TABLE "prodotti" (
    "id" INTEGER,
    "productid" TEXT,
    "Active" TEXT,
    "Name" TEXT,
    "Categories" TEXT,
    "Price_tax_excluded" TEXT,
    "Tax_rules_ID" TEXT,
    "Wholesale_price" TEXT,
    "On_sale" TEXT,
    "Discount_amount" TEXT,
    "Discount_percent" TEXT,
    "Discount_from" TEXT,
    "Discount_to" TEXT,
    "Reference" TEXT,
    "Supplier_reference" TEXT,
    "Supplier" TEXT,
    "Manufacturer" TEXT,
    "EAN13" TEXT,
    "UPC" TEXT,
    "Ecotax" TEXT,
    "Width" TEXT,
    "Height" TEXT,
    "Depth" TEXT,
    "Weight" TEXT,
    "Delivery_time_of_in_stock_products" TEXT,
    "Delivery_time_of_out_of_stock_products_with_allowed_orders" TEXT,
    "Quantity" TEXT,
    "Minimal_quantity" TEXT,
    "Low_stock_level" TEXT,
    "Receive_a_low_stock_alert_by_email" TEXT,
    "Visibility" TEXT,
    "Additional_shipping_cost" TEXT,
    "Unity" TEXT,
    "Unit_price" TEXT,
    "Summary" TEXT,
    "Description" TEXT,
    "Tags" TEXT,
    "Meta_title" TEXT,
    "Meta_keywords" TEXT,
    "Meta_description" TEXT,
    "URL_rewritten" TEXT,
    "Text_when_in_stock" TEXT,
    "Text_when_backorder_allowed" TEXT,
    "Available_for_order" TEXT,
    "Product_available_date" TEXT,
    "Product_creation_date" TEXT,
    "Show_price" TEXT,
    "Image_URLs" TEXT,
    "Image_alt_texts" TEXT,
    "Delete_existing_images" TEXT,
    "Feature" TEXT,
    "Available_online_only" TEXT,
    "Condition" TEXT,
    "Customizable" TEXT,
    "Uploadable_files" TEXT,
    "Testo_fields" TEXT,
    "Out_of_stock_action" TEXT,
    "Virtual_product" TEXT,
    "File_URL" TEXT,
    "Number_of_allowed_downloads" TEXT,
    "Expiration_date" TEXT,
    "Number_of_days" TEXT,
    "ID_Name_of_shop" TEXT,
    "Advanced_stock_management" TEXT,
    "Depends_on_stock" TEXT,
    "Warehouse" TEXT,
    "Accessories" TEXT,
    PRIMARY KEY("id")
    );


    Issue:

    In the exported CSV file, the data seems to be shifted to the right, and the columns are not aligned correctly. I’ve attempted to adjust the column indices in my code (as shown above), but the problem persists. You can see the issue in the attached screenshot below:

    Screenshot of the problem:

    What I’ve Tried:

    I modified the row's data manually before writing it to the CSV file (by swapping column values) using the indices.
    The column headers are correctly defined in the code, but when I open the CSV file, the data doesn't match up with the headers.


    Question: Has anyone experienced this issue before? How can I fix the shifted columns when exporting data from SQLite to CSV?

    Continue reading...

Compartilhe esta Página