Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📊 Unit 1 – DataFrame  ·  Lesson 11

Importing & Exporting CSV

What is a CSV file?

A CSV (comma-separated values) file stores a table as plain text – one row per line, values separated by commas. Excel, Google Sheets and MySQL can all open and save CSV, so it is the easiest way to move data into pandas.

Excel / Sheetsresult.csvpd.read_csv()DataFramedf.to_csv()new CSV
Data moves in and out of pandas through CSV

Export: to_csv()

Python
import pandas as pd
df = pd.DataFrame({'Roll': [1, 2, 3, 4], 'Name': ['Asha', 'Ravi', 'Neha', 'Om'],
                   'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74]})
df.to_csv('result.csv', index=False)          # export without the row index
print(open('result.csv').read())
Roll,Name,Maths,IP 1,Asha,78,88 2,Ravi,92,81 3,Neha,65,95 4,Om,88,74

Import: read_csv()

Python
import pandas as pd
df = pd.read_csv('result.csv')                # import
print(df)
print(df.shape, df.columns.tolist())
Roll Name Maths IP 0 1 Asha 78 88 1 2 Ravi 92 81 2 3 Neha 65 95 3 4 Om 88 74 (4, 4) ['Roll', 'Name', 'Maths', 'IP']

Useful read_csv options

ParameterUse
sepSeparator character (default ",")
headerRow number of column names; None if there is no header
namesList of column names to use
index_colColumn to use as the row index
usecolsRead only these columns
nrowsRead only the first n rows
Python
import pandas as pd
df = pd.read_csv('result.csv', index_col='Roll')   # use a column as row index
print(df)
print(pd.read_csv('result.csv', usecols=['Name', 'IP'], nrows=2))
Name Maths IP Roll 1 Asha 78 88 2 Ravi 92 81 3 Neha 65 95 4 Om 88 74 Name IP 0 Asha 88 1 Ravi 81

File without a header row

Python
import pandas as pd
with open('nohead.csv', 'w') as f:
    f.write('101,Pen,10\n102,Pencil,5\n103,Eraser,3\n')
items = pd.read_csv('nohead.csv', header=None, names=['Code', 'Item', 'Price'])
print(items)
Code Item Price 0 101 Pen 10 1 102 Pencil 5 2 103 Eraser 3

Other separators

Python
import pandas as pd
df = pd.read_csv('result.csv')
df.to_csv('result_semicolon.csv', sep=';', index=False)
print(open('result_semicolon.csv').read().splitlines()[:2])
back = pd.read_csv('result_semicolon.csv', sep=';')
print(back.head(2))
['Roll;Name;Maths;IP', '1;Asha;78;88'] Roll Name Maths IP 0 1 Asha 78 88 1 2 Ravi 92 81

Complete CSV program

Python
import pandas as pd
df = pd.read_csv('result.csv')
df['Total'] = df['Maths'] + df['IP']
df['Percent'] = (df['Total'] / 2).round(1)
toppers = df[df['Percent'] >= 82]
toppers.to_csv('toppers.csv', index=False)
print(df)
print('Saved', len(toppers), 'toppers')
print(open('toppers.csv').read())
Roll Name Maths IP Total Percent 0 1 Asha 78 88 166 83.0 1 2 Ravi 92 81 173 86.5 2 3 Neha 65 95 160 80.0 3 4 Om 88 74 162 81.0 Saved 2 toppers Roll,Name,Maths,IP,Total,Percent 1,Asha,78,88,166,83.0 2,Ravi,92,81,173,86.5

Frequently Asked Questions

Why use index=False in to_csv()?
Without it pandas also writes the row index (0, 1, 2…) as an extra unnamed first column.
How do I read a CSV file that has no header?
Use header=None, and give column names with names=[...].
Where should the CSV file be kept?
In the same folder as the Python program, or give the full path, e.g. pd.read_csv("C:/data/result.csv").
← Class 12 Informatics Practices
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDescriptive Statistics Your progress: 11 / 25 (44%) · Lesson 12 / 25 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free