gpt-4-0314· OpenAI
Arena Human Preference 55K
Write a Python function that accepts a URL to a CSV file, downloads it and loads it into…
- User
Write a Python function that accepts a URL to a CSV file, downloads it and loads it into a SQLite database, creating a table with the correct columns
- Assistant
To achieve this, you can use the
requests,csv,sqlite3, andiolibraries in Python. You can install therequestslibrary usingpip install requestsif you don't have it already. Here's a Python function that downloads a CSV file from the given URL and stores it in a SQLite database:import requests import csv import sqlite3 from io import StringIO def download_csv_to_sqlite(url, db_name): # Download the CSV file response = requests.get(url) response.raise_for_status() # Load the CSV content into a StringIO object csv_content = StringIO(response.text) # Read the CSV using the csv.reader csv_reader = csv.reader(csv_content) # Extract the headers (first row) from the CSV headers = next(csv_reader) # Create a SQLite database connection conn = sqlite3.connect(db_name) cursor = conn.cursor() # Create a table with the correct columns table_name = 'csv_data' columns = ', '.join([f'"{header}" TEXT' for header in headers]) create_table_query = f'CREATE TABLE IF NOT EXISTS {table_name} ({columns});' cursor.execute(create_table_query) # Insert the CSV data into the table for row in csv_reader: cursor.execute(f'INSERT INTO {table_name} VALUES ({",".join(["?" for _ in row])});', row) # Commit the changes and close the database connection conn.commit() conn.close() # Example usage: url = 'https://example.com/data.csv' db_name = 'data.sqlite' download_csv_to_sqlite(url, db_name)Please make sure to replace
https://example.com/data.csvwith the actual URL of the CSV file you want to download, and provide an appropriate SQLite database name, such asdata.sqlite.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.