Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Csv –

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 7

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 csv.reader()
4. Use the reader object to iterate over each line of the CSV file.
Example:
import csv
with open(‘example.csv’, mode=‘r’) as file:
csv_reader = csv.reader(file)
header = next(csv_reader)
print(header)
rows=[]
for row in csv_reader:
rows.append(row)
print(rows)
file.close()
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 csv.reader object to rad the CSV file
csvreader=csv.reader(f)
* Extract the field names
header=[]
header=next(csvreader)
header
* Extract the rows/records
rows=[]
for row in csvreader:
rows.append(row)
rows
* Close the files. f.close()
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 csv.Reader() function:

The csv.reader() 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 csv.Writerow() function:
Syntax:
csv.writer(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 = csv.writer(csv_file)
csvwriter.writerow(field_name)
csvwriter.writerows(rows_entries)

You might also like