The Wayback Machine - https://web.archive.org/web/20240530090251/https://www.geeksforgeeks.org/how-to-import-and-export-data-using-csv-files-in-postgresql/
Open In App

How to import and export data using CSV files in PostgreSQL

Last Updated : 23 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 establishment
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
conn.autocommit = True
  
# Creating a cursor object
cursor = conn.cursor()
  
# query to create a table
sql = ''' CREATE TABLE demo
(
    id INT,
    name VARCHAR(50),
    city VARCHAR(50),
    age INT
); '''
  
# executing above query
cursor.execute(sql)
print("Table has been created successfully!!")
  
# Closing the connection
conn.close()


Output:

Table has been created successfully!!

Importing data using a CSV file

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 establishment
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
conn.autocommit = True
  
# Creating a cursor object
cursor = conn.cursor()
  
# query to import data from given csv
sql = '''COPY demo FROM 
        'C:\\Users\\DELL\\Downloads\\Demo_data.csv' 
        DELIMITER ',' CSV HEADER'''
  
# executing above query
cursor.execute(sql)
  
# Display the table
cursor.execute('SELECT * FROM demo')
print(cursor.fetchall())
  
# Closing the connection
conn.close()


Output:

[(1, ‘Harry’, ‘Delhi’, 29), (2, ‘Mira’, ‘Mumbai’, 24), (3, ‘Emma’, ‘Bangalore’, 30), (4, ‘Kevin’, ‘Mumbai’, 19)]

Exporting data using CSV file

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 establishment
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
conn.autocommit = True
  
# Creating a cursor object
cursor = conn.cursor()
  
# query to export table into csv
sql = '''COPY demo TO 
        'C:\\Users\\DELL\\Downloads\\Exported_data.csv' 
        DELIMITER ',' CSV HEADER'''
  
# executing above query
cursor.execute(sql)
  
# Closing the connection
conn.close()


The exported CSV will look like this:



Previous Article
Next Article

Similar Reads

Python - Import CSV into PostgreSQL
In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the "creat
2 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
PyMongoArrow: Export and Import MongoDB data to Pandas DataFrame and NumPy
If you are a data scientist or a Python developer who sometimes wears the data scientist hat, it is highly likely that at some point you were required to work with these three tools &amp; technologies: Pandas, NumPy and MongoDB. Pandas: Pandas is a fast, powerful and easy-to-use open-source data analysis and manipulation tool, built on top of the P
8 min read
How to export Pandas DataFrame to a CSV file?
Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file. DataFrame.to_csv() Syntax : to_csv(parameters) Parameters : path_or_buf : File path or object, if None is provided the result is returned as a string. sep : String of length 1. Field delimiter for the output file. na_
3 min read
Export Pandas dataframe to a CSV file
Suppose you are working on a Data Science project and you tackle one of the most important tasks, i.e, Data Cleaning. After data cleaning, you don't want to lose your cleaned data frame, so you want to save your cleaned data frame as a CSV. Let us see how to export a Pandas DataFrame to a CSV file. Pandas enable us to do so with its inbuilt to_csv(
2 min read
Export Specific Columns in DataFrame to CSV File
A data frame is a tabular data structure similar to a spreadsheet. It has rows and columns. CSV (Comma-Separated Values) is a plain text file format used for storing tabular data. Each line in a CSV file represents a row of data, and the values within a line are separated by commas. This article explores two methods for exporting selected columns f
3 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
How to import CSV file in SQLite database using Python ?
In this article, we'll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students. [caption width="800"]Contents of the CSV file[/caption] Approach: Importing necessary modulesRead data from CSV file Di
2 min read
Different ways to import csv file in Pandas
CSV files are the "comma separated values", these values are separated by commas, this file can be viewed as an Excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can be in CSV file format. Let's see the different ways to import csv files in
3 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
Practice Tags :