'Retrieve table from .sql file with Pandas

How can I make Pandas take a .sql file and turn it into a DataFrame, to then be exported to .csv?

I've searched online and found something like this:

import pandas as pd
import sqlite3

con = sqlite3.connect('path/to/file.sql')
data = pd.read_sql(
    'SELECT * FROM tablename', con
)
data.to_csv('path/to/file.csv')
con.close()

I've tried that (with changed file paths of course), but it throws a DatabaseError, saying that file is not a database. I am unsure what this means.

My .sql file looks something like this, though much longer:

CREATE TABLE tablename(
    one INTEGER,
    two TEXT PRIMARY KEY
);
INSERT INTO tablename(one, two) VALUES (1, 'hello world');
SELECT * FROM tablename -- I have tried with and without the SELECT statement

I can confirm that it is a valid SQL file.

Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source