Chapter5 3CSVFile
Chapter5 3CSVFile
Chapter5 3CSVFile
CSV File:
Purpose:
CSV is a simple text file in a human readable format which is extensively used to:
Store tabular data as text in a spreadsheet or database
Sharing data through import and export of file
File Elements:
Records - Each line in a file is known as data/record. Each line is separated by a newline (‘\n’).
Fields - Each record consists of one or more fields. Each field is separated by a delimiter (by
default comma).
Every records have same number of fields.
The first line of the file generally stores Headers or Column names, rest of the lines contains
data values for each record.
Application:
CSV organizes large unstructured data into a properly structured and systematic form.
Since CSV files formats are of plain text format, it makes it very easy for website developers to
create applications that implement CSV.
Advantages:
1. Small in size
2. Fast to handle
3. Human readable and easy to edit manually
4. Easy to generate and import onto a spreadsheet or database
5. Simple to implement and parse
6. Processed by almost all existing applications
Disadvantages:
1. Not fully standardized
2. Problem arises if the values contain quotation (Single or Double quotes), comma or newline
characters within data itself
3. Not applicable for those systems which supports each record with different number of fields.
Example:
1. Import CSV Module – Python built-in CSV module should be imported at first to deal file
CSV file using the following statement:
import csv
2. Opening a CSV file – Using built-in open() like any other text file the file is opened in the
mode specified (by default, reading mode). Filename must have extension as .csv and open()
returns a file object to access file. CSV file can be opened as follows:
3.
file_object = open(“<path//>Filename.csv”, file_mode)
Or,
with open(“<path//>Filename.csv”, file_mode) as file_object:
# Access file (Explicit calling close() not required)
4. Reading a CSV file – For reading a CSV file following functions are required:
Step 1: csv.reader() -- This function creates a special type of object i.e. reader object to access
the CSV file. The reader object is iterable and gives us access to each line of the CSV
file as a list of fields.
Method 1 : next() -- This built-in function can be directly called on reader object to read
the next line of the CSV file. next() returns the current row and advances the iterator to the
next row.
record = next(csv_reader_object)
Method 2 : Use for loop to read each lines of the file as a list of the fields
5. Writing a CSV file – For writing into a CSV File following functions are required:
Step 1: csv.writer() -- This function returns a writer object that converts the user's data (can
include number or text or both) into a delimited string which can be used to write into CSV file.
where delimiter parameter is optional and have default value ‘,’ that can be changed.
Method 1 : writerow() – This function allows to write a list of fields i.e. only one record at
a time to the file.
csv_writer_object.writerow(['Field1', 'Field2', … ,'Fieldn'])
Method 2 : writerows() – This function allows to write all the lines i.e. list of all records
(2D list) to the file at one go.
where Recordi = ['Fieldi1', 'Fieldi2', … ,'Fieldin'] if a csv file contains m records and each
record contains n fields.
6. Closing a CSV file – If file is opened using open() directly then it should be closed after
operation on file is completed.
file_object.close()
import csv
Output:
# OPEN AND READ FILE
['EMP_ID', 'NAME', 'DEPT', 'SALARY']
file = open("Employee.csv",'r')
['1001', 'Sonam Dutta', 'Computer', '45000']
csv_rd = csv.reader(file)
['1002', 'Sourav Basu', 'Physics', '62000']
c=0
Records retrieved successfully!
for rec in csv_rd:
Total no. of lines in the file = 3
print(rec)
c += 1
print("Records retrieved successfully!")
print("Total no. of lines in the file = ", c)
file.close()
Method II : Display records without any delimiter or special characters
import csv
The program for appending records in an existing file is similar to writing records in a new file i.e.
Program#1.
The only difference is here the file should be opened in appending mode as following:
file = open("Employee.csv",'a')
Output:
# Display the details and total count of employees who belong to a given department.
import csv
5. Searching and updating an existing record from CSV File through Python:
# Input Employee ID from user to search for. If found then update salary.
import csv
6. Searching and deleting an existing record from CSV File through Python:
import csv
__________________