Python Read CSV File with Example Tutorials
Hi Guys,
In this tutorial, you will learn python to read CSV examples. you'll learn python to get data from CSV files. We will look at an example of a python read CSV file example. I explained simply about the python program to read data from CSV files. You just need to some steps to done read data from the CSV file python.
![]() |
Reading a CSV (Comma Separated Values) file in Python is a very common task for data analysis and manipulation. One of the most popular libraries for reading and writing CSV files in Python is the "pandas" library.
Here is an example of how to use the "pandas" library to read a CSV file in Python:
import pandas as pd
# Read CSV file
df = pd.read_csv('example.csv')
# Print the dataframe
print(df)
In this example, we first import the "pandas" library using the "import" statement. Next, we use the "read_csv()" function to read the contents of the CSV file 'example.csv' into a data frame. Finally, we print the data frame using the "print()" function.
You can also specify the separator used in the CSV file if it is not ','. For example, if you are using a tab-separated file, you can use the following code:
df = pd.read_csv('example.tsv', sep='\t')
You can also specify the row number to be used as the header using the header
parameter, if the file doesn't have a header.
df = pd.read_csv('example.csv', header=0)
You can also specify the names of the columns to be used if the file doesn't have a header or you want to use your own names.
df = pd.read_csv('example.csv', names=['col1','col2','col3'])
You can also skip certain rows, for example, if the first two rows contain metadata and not data. Copy code
This is a basic example of how to read a CSV file in Python using the "pandas" library. There are many more options and features that you can use when reading and working with CSV files in Python.
Example
Python Read CSV File
main.py
from csv import reader
# open demo.csv file in read mode
with open('demo.csv', 'r') as readObj:
# pass the file object to reader() to get the reader object
csvReader = reader(readObj)
# Iterate over each row in the csv using reader object
for row in csvReader:
# row variable is a list that represents a row in csv
print(row)
Output
['ID', 'Name', 'Email']
['1', 'Hariom Kumawat, ‘hariom@gmail.com']
['2', 'Nileshl Patel', 'nilesh@gmail.com']
['3', 'Piyush Kamani', 'piyush@gmail.com']
Comments
Post a Comment