0% found this document useful (0 votes)
55 views7 pages

Python CSV File Handling Guide

Uploaded by

vaniashrafali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views7 pages

Python CSV File Handling Guide

Uploaded by

vaniashrafali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

CSV – “COMMA SEPARATED

VALUES”
CSV FILE:
A CSV stands for “ comma separated values”, which is defined
as a simple file format that uses specific structuring to arrange tabular
data. It stores tabular data such as spreadsheet or database in plain text.
A csv file opens into the excel sheet, and the rows and columns
data define the standard format.
To work with CSV files in Python, you can use the built-in CSV
module and Python’s open() function:
To work with CSV files in Python, you can use the built-in CSV module and
Python’s open() function:

1. Import the csv module


2. Open the csv files as a text file using open()
3. Create a CSV reader object using [Link]()
4. Use the reader object to iterate over each line of the CSV file.
Example:
import csv
with open(‘[Link]’, mode=‘r’) as file:
csv_reader = [Link](file)
header = next(csv_reader)
print(header)
rows=[]
for row in csv_reader:
[Link](row)
print(rows)
[Link]()
Steps to Read CSV files in python using csv reader:

* Import the CSV library. import csv


* Open the CSV file
f=open(“ .csv”)
type(f)
* Use the [Link] object to rad the CSV file
csvreader=[Link](f)
* Extract the field names
header=[]
header=next(csvreader)
header
* Extract the rows/records
rows=[]
for row in csvreader:
[Link](row)
rows
* Close the files. [Link]()
Syntax:

With open(filename, mode) as alias_filename:


Mode:
* ‘r’ – to read an existing file,
* ‘w’ – to create a new file if the given file
doesn’t exist and write to it,
* ‘a’ – to append to existing file content,
* ‘+’ – to create a new file for reading and
writing.
Using [Link]() function:

The [Link]() module is used to read the csv


file. It takes each row of the file and makes a list of
all the columns.
OUTPUT:
[‘Name’, ‘Age’, ‘ City’]
[‘Ram’, ‘27’, ‘Mumbai’]
[‘Bheem’, ‘29’, ‘ Pune’]
Using [Link]() function:
Syntax:
[Link](csv_file,dialect=‘excel’,**optional_params)
* writerow() – method is used to write a single row at a time
into a CSV file.
* writerows() – method is used to write multiple rows at a time.
Example:
import csv
field_name=[‘Name’, ‘ Age’, ‘ City’]
rows_entries=[[‘Ram’, ‘27’, ‘Mumbai’],
[‘Bheem’, ‘29’, ‘ Pune’]]
file_name=“student_detail.csv”
with open(file_name, ’w’) as csv_file:
csv_writer = [Link](csv_file)
[Link](field_name)
[Link](rows_entries)

You might also like