0% found this document useful (0 votes)
39 views

CSV Files

Uploaded by

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

CSV Files

Uploaded by

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

CSV FILES

A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to arrange
tabular data. Because it’s a plain text file, it can contain only actual text data as ASCII or Unicode characters.

The structure of a CSV file is given away by its name. Normally, CSV files use a comma to separate each specific
data value.

CSV files are normally created by programs that handle large amounts of data. They are a convenient way to
export data from spreadsheets and databases as well as import or use it in other programs.

CSV files are very easy to work with programmatically. Any language that supports text file input and string
manipulation (like Python) can work with CSV files directly.

Data is stored in rows and columns or tabular form. Thus it is easy to export from database or spreadsheets.

CSV files can be easily imported to other programs.

The extension of CSV files is .csv.

The csv library provides functionality to both read from and write to CSV files. Designed to work out of the box
with Excel-generated CSV files, it is easily adapted to work with a variety of CSV formats. The csv library contains
objects and other code to read, write, and process data from and to CSV files.

Advantages of CSV:

1. It is easy to generate.
2. It is human readable and easy to edit.
3. It is faster to handle.
4. It is smaller in size.
5. It is simple to implement and parse.
6. It is processed by almost all existing applications.

Disadvantages of CSV:

1. No standard way to represent binary data.


2. Poor support of special characters.
3. No standard way to represent control characters.
4. Problems with importing CSV into SQL (no distinction between NULL and quotes).
5. Lack of universal standard.

How to create CSV files:

A CSV file, which is a “comma separated values” file, allows you to save your data in a table-structured format,
which is useful when you need to manage a large database.

CSV files can be created in three ways:

1. Using Spreadsheet (Microsoft Excel/OpenOffice Calc/ Google Spreadsheets.


2. Using Text Editor (Notepad).
3. Using Python program.

Using Python Program:

Working with CSV file in Python:

1. To perform read and write operation with CSV file, we must import CSV module.
2. open() function is used to open file, and return file object.

The file access modes ‘r’, ‘w’, ‘a’, ‘r+’, ‘w+’, ‘a+’ is to be used while opening csv files.
Opening / closing CSV file:

Opening a csv file:


Eg. F=open(“Stu.csv”,”r”)
F=open(“Stu.csv”,”w”)

Closing a csv file:


Eg. F.close()

Role of argument newline while opening csv files:

 An additional argument ‘newline’ can be given in the open() function while opening a CSV file. the
newline argument specifies how Python would handle newline characters while working with CSV files
in different operating systems.
 Different operating system stores EOL characters differently.

Note: Additional optional argument as newline=”” (null string or empty string) with file open() will ensure
that no translation of EOL characters takes place.

Python csv module:

While working with CSV files, the csv module has to be imported in the program using import csv.

The csv modules provide 2 types of objects or functions to perform read and write operations on CSV file.

1. reader(): To read from csv file.


2. writer(): To write into a csv file.

Writing into CSV files:

To write to a CSV file in Python, csv.writer() is used. The csv.writer() returns a writer object that converts the
user’s data into a delimited string. This string can later be used to write into CSV files.

The writer() object provides the following two methods to write data:

# Creating CSV file through Python program


# Using writerow() function

Write a program to write student’s detail (RollNo, Name, Marks) into a CSV file ‘Students1.csv’.

import csv
def WRITE():
F=open(“Students1.csv”, “w”, newline=””) # F=open(“Students1.csv”, “w”)
Swriter=csv.writer(F) # Swriter=csv.writer(F, delimiter=”:”)
Swriter.writerow([‘RNo’, ‘Name’, ‘Marks’]) # To write header
while True:
R=int(input(“Enter Roll No.:”))
N=input(“Enter Name:”)
M=int(input(“Enter Marks:”))
data=[R, N, M]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()

OR

import csv
def WRITE():
header=['eno','name','salary']
rows=[
[15,'Anubhav Singh',45000],
[20,'Shivesh Tripathi',55000],
[40,'Abhinav Sagar',62000],
[45,'Dhruv Sharma',48000],
[60,'Aryan Rana',64000],
]
F=open('emp3.csv','w')
Swriter=csv.writer(F)
Swriter.writerow(header) # To write header
for r in rows:
Swriter.writerow(r)
F.close()
WRITE()

In the above example the csv file will be created with the following content:
# Creating CSV file through Python program
# Using writerows() function

import csv
def WRITE():
F=open(“Students1.csv”, “w”, newline=””) # F=open(“Students1.csv”, “w”)
rows=[ ]
Swriter=csv.writer(F) # csv_writer=csv.writer(F, delimiter=”:”)
rows.append([‘RNo’, ‘Name’, ‘Marks’]) # To write header
while True:
R=int(input(“Enter Roll No.:”))
N=input(“Enter Name:”)
M=int(input(“Enter Marks:”))
data=[R, N, M]
rows.append(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
Swriter.writerows(rows)
F.close()
WRITE()

OR
import csv
def WRITE():
header=['eno','name','salary']
rows=[
[15,'Anubhav Singh',45000],
[20,'Shivesh Tripathi',55000],
[40,'Abhinav Sagar',62000],
[45,'Dhruv Sharma',48000],
[60,'Aryan Rana',64000],
]
F=open('emp3.csv','w')
Swriter=csv.writer(F)
Swriter.writerow(header) # To write header
Swriter.writerows(rows)
F.close()
WRITE()

Writing to a CSV File with Tab Delimiter


# Program to write with tab delimiter
import csv
def WRITE()
f=open("stud.csv", 'w')
mywriter=csv.writer(f, delimiter='\t')
mywriter.writerow(["rno","name","marks"])
while True:
rno=int(input("Enter roll no no "))
name=input("Enter name ")
marks=int(input("Enter marks "))
mywriter.writerow([rno,name,marks])
choice=input("Enter more records Y/N : ")
if (choice.upper()=='N'):
break
f.close()

WRITE()

In the above example the CSV file will be created with the following content:

Reading from csv File:

The reader() function takes a file object and returns a csv.reader object that can be used to iterate
over the contents of a CSV file.

Example:

Suppose we have a CSV file named student.csv in the current directory with the following entries.

import csv
def READ():
f=open("student.csv", 'r')
Sreader=csv.reader(f)
for r in Sreader:
print(r)
READ()

The output of the above program is:


Here, we have opened the student.csv file in reading mode: Then, the csv.reader() is used to read the file,
which returns an iterable reader object. The reader object is then iterated using a for loop to print the contents
of each row.

In the above example, we are using the csv.reader() function in default mode for CSV files having comma
delimiter.

However, the function is much more customizable.

Suppose our CSV file was using tab as a delimiter.

To read such files, we can pass optional parameters to the csv.reader() function

Example: Reading CSV file with tab delimiter

import csv
f=open("student.csv", 'r')
Sreader=csv.reader(f,delimiter='\t')
for r in reader:
print(r)

Note: Each line in the CSV file is returned as a list of strings.

Q. Write a function to write and read data from a csv file “Items.csv” consisting of ItemNo, ItemName,
Quantity and Price.

import csv
def WRITE():
F=open(“Items.csv”, “w”, newline=””)
Swriter=csv.writer(F)
Swriter.writerow([‘ItemNo’, ‘ItemName’, ‘Quantity’, ‘Price’])
while True:
INo=int(input(“Enter Item No.:”))
IName=input(“Enter Item Name:”)
Qty=int(input(“Enter Quantity:”))
P=int(input(“Enter Price:”))
data=[INo, IName, Qty, P]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()

2)

import csv
def READ():
F=open(“Items.csv”, “r)
Sreader=csv.reader(F)
for r in Sreader:
print(r)
READ()

Q. A CSV file “Countries.csv” contains data in the following order - Country, Capital, Code
Sample of “Countries.csv” is given below:
India, New Delhi, II
US, Washington, UU
Malaysia, Kualampur, MM
France, Paris, FF
Write Python functions to write and read from the CSV file.

1)

import csv
def WRITE():
F=open(“Countries.csv”, “w”, newline=””)
Swriter=csv.writer(F)
Swriter.writerow([‘Country’, ‘Capital’, ‘Code’])
while True:
Co=input(“Enter the Country:”)
Cp=input(“Enter the Capital:”)
Cd=input(“Enter Country Code:”)
data=[Co, Cp, Cd]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()

2)

import csv
def READ():
F=open(“Countries.csv”, “r)
Sreader=csv.reader(F)
for r in Sreader:
print(r)
READ()
Q. Write a function to write to the file “Product.csv” with the data given below.
The first record of the file should be PID, PName, Cost, quantity
Sample of Product.csv is given below:
[P1, Brush, 50, 200]
[P2, Toothpaste, 120, 150]

import csv
def WRITE():
F=open(“Product.csv”, “w”, newline=””)
Swriter=csv.writer(F)
Swriter.writerow([‘PID’, ‘PName’, ‘Cost’, ‘Quantity’])
while True:
ID=input(“Enter Product ID:”)
Name=input(“Enter Product Name:”)
C=int(input(“Enter Product Cost:”))
Qty=int(input(“Enter Quantity:”))
data=[ID, Name, C, Qty]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()

You might also like