Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

CSV File Handling

CSV is a file format used to store tabular data like a spreadsheet or database. Each line is a data record made of fields separated by commas. Python's csv module can read, write, and modify CSV files. Examples show reading a CSV, writing to one, and writing a dictionary to a CSV.

Uploaded by

Bikash Ray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

CSV File Handling

CSV is a file format used to store tabular data like a spreadsheet or database. Each line is a data record made of fields separated by commas. Python's csv module can read, write, and modify CSV files. Examples show reading a CSV, writing to one, and writing a dictionary to a CSV.

Uploaded by

Bikash Ray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

What is a CSV?

CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a
spreadsheet or database. A 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 name for this file
format.
For working CSV files in Python, there is an inbuilt module called csv.

Example 1: Reading a CSV file


# importing csv module
import csv

# csv file name


filename = "aapl.csv"

# initializing the titles and rows list


fields = []
rows = []

# reading csv file


with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)

# extracting field names through first row


fields = next(csvreader)

# extracting each data row one by one


for row in csvreader:
rows.append(row)

# get total number of rows


print("Total no. of rows: %d"%(csvreader.line_num))

# printing the field names


print('Field names are:' + ', '.join(field for field in fields))
# printing first 5 rows
print('\nFirst 5 rows are:\n')
for row in rows[:5]:
# parsing each column of a row
for col in row:
print("%10s"%col,end=" "),
print('\n')

Example 2: Writing to a CSV file


# importing the csv module
import csv

# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']

# data rows of csv file


rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]

# name of csv file


filename = "university_records.csv"

# writing to csv file


with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)

# writing the fields


csvwriter.writerow(fields)

# writing the data rows


csvwriter.writerows(rows)
Example 3: Writing a dictionary to a CSV file
# importing the csv module
import csv

# my data rows as dictionary objects


mydict =[{'branch': 'COE', 'cgpa': '9.0',
'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1',
'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3',
'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5',
'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8',
'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1',
'name': 'Sahil', 'year': '2'}]

# field names
fields = ['name', 'branch', 'year', 'cgpa']

# name of csv file


filename = "university_records.csv"

# writing to csv file


with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(csvfile, fieldnames = fields)

# writing headers (field names)


writer.writeheader()

# writing data rows


writer.writerows(mydict)

You might also like