How to import and export data using CSV files in PostgreSQL - GeeksforGeeks

23 Sep, 2021
In this article, we are going to see how to import and export data using CSV file in PostgreSQL, the data in CSV files can be easily imported and exported using PostgreSQL.
To create a CSV file, open any text editor (notepad, vim, atom). Write the column names in the first line. Add row values separated by commas to the corresponding columns in the next lines. Save the file as Demo_data.csv as shown below.
Now create a new table using psycopg2 where we will import the data from the CSV file:
Python3
import psycopg2  # connection establishmentconn = psycopg2.connect(    database="postgres",    user='postgres',    password='password',    host='localhost',    port='5432')  conn.autocommit = True  # Creating a cursor objectcursor = conn.cursor()  # query to create a tablesql = ''' CREATE TABLE demo(    id INT,    name VARCHAR(50),    city VARCHAR(50),    age INT); '''  # executing above querycursor.execute(sql)print("Table has been created successfully!!")  # Closing the connectionconn.close()
Output:
Table has been created successfully!!
We use COPY command with FROM keyword to import the contents of the CSV file into a new table.
Syntax: COPY <table name> FROM ‘location + file_name’ DELIMITER ‘,’ CSV HEADER;
Where:
<table name> – name of the table where we want to import data.
‘location + file_name’ – full path of the CSV file from which we are importing data (make sure you have ‘read’ access to the file).
DELIMITER ‘,’ – specifies the delimiter which is comma (,)
CSV – specifies the format of the file from which we are importing data.
HEADER – specifies that we have a header row in our .csv file and while importing we should ignore the first row.
Example:
Python3
import psycopg2  # connection establishmentconn = psycopg2.connect(    database="postgres",    user='postgres',    password='password',    host='localhost',    port='5432')  conn.autocommit = True  # Creating a cursor objectcursor = conn.cursor()  # query to import data from given csvsql = '''COPY demo FROM         'C:\\Users\\DELL\\Downloads\\Demo_data.csv'         DELIMITER ',' CSV HEADER'''  # executing above querycursor.execute(sql)  # Display the tablecursor.execute('SELECT * FROM demo')print(cursor.fetchall())  # Closing the connectionconn.close()
Output:
[(1, ‘Harry’, ‘Delhi’, 29), (2, ‘Mira’, ‘Mumbai’, 24), (3, ‘Emma’, ‘Bangalore’, 30), (4, ‘Kevin’, ‘Mumbai’, 19)]
To export data from a table into a CSV file, we use TO keyword with the COPY command. 
Syntax: COPY <table name> TO ‘location + file_name’ DELIMITER ‘,’ CSV HEADER;
Here, <table name> is the table from which we are exporting data.
‘location + file_name’ contains the path of the CSV file into which we want to export the data. Make sure you have ‘write’ access to the file.
Example:
Python3
import psycopg2  # connection establishmentconn = psycopg2.connect(    database="postgres",    user='postgres',    password='password',    host='localhost',    port='5432')  conn.autocommit = True  # Creating a cursor objectcursor = conn.cursor()  # query to export table into csvsql = '''COPY demo TO         'C:\\Users\\DELL\\Downloads\\Exported_data.csv'         DELIMITER ',' CSV HEADER'''  # executing above querycursor.execute(sql)  # Closing the connectionconn.close()
The exported CSV will look like this:
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()