Экстракт Python CSV из SQLite DBPython

Программы на Python
Anonymous
 Экстракт Python CSV из SQLite DB

Сообщение Anonymous »

Я пытаюсь экспортировать данные из базы данных SQLite в файл CSV с использованием Python, но столбцы в экспортированном файле CSV смещаются. Я попытался решить проблему, настраив заказ столбца в коде, но проблема сохраняется. Вот код, с которым я работаю: < /p>
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}")
< /code>
Моя таблица sqlite < /p>
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")
);
< /code>
Проблема: < /p>
В экспортированном файле CSV данные, по -видимому, смещены вправо, и столбцы не выровнены правильно. Я попытался настроить индексы столбцов в моем коде (как показано выше), но проблема сохраняется. Вы можете увидеть проблему на прикрепленном скриншоте ниже:
Скриншот проблемы:
Что я пробовал:
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.
< /code>
Вопрос: кто -нибудь испытал эту проблему раньше? Как я могу исправить смещенные столбцы при экспорте данных с SQLite в CSV?

Подробнее здесь: https://stackoverflow.com/questions/793 ... -sqlite-db

Вернуться в «Python»