0% found this document useful (0 votes)
20 views9 pages

Data File Handling Working With CSV Files

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 9

Unit I: Computational Thinking and Programming - 2

Chapter-8
: File
File Handling
Handling -> CSV File
In this tutorial we will discuss the following topics

S.No. Topics

1 File Handling -> CSV Files

2 Python: Writing into CSV files

3 Writing into CSV using loop:

4 Python: Reading from CSV files

5 Appending to CSV files

6 Copy data from one file to another

7 Searching Record in CSV file (Search By Roll number)

8 Deleting record from CSV file by field value

Page 1 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
: File
Python: Handling
File Handling -> CSV Files
What is CSV file?
 In this type of file, there is no terminator for a
line and the data is stored after converting it into
machine understandable binary language.
 Operations on binary files are faster as no
translation required.
 Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf,
etc., all of them constitute binary files.

Some of the most common access modes are listed below:


There are 3 main modes in which the files can be opened: Read, Write and Append
mode.

Read mode (denoted by ‘r’): It reads contents from a file. The file should exist else it
gives an error.

Write mode (denoted by ‘w’): It writes to a CSV file. If the file exists, it clears it and
starts writing to it from the first row. Else, if the file does not exist, it is created and
then the data is written to it.

Append mode (denoted by ‘a’): It writes rows to a pre-existing file. It is different


from write mode as it does not clear the existing rows of the CSV file, it just adds the
rows below them.

Operations performed using CSV files:

a) Reading from CSV file


b) Writing to CSV File
c) Appending record ( inserting record at the end of the file)
d) Copying a file
Page 2 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
: File
e) Searching Record in CSVfile Handling
f) Deleting record from CSVfile
g) Modification/ Updation in CSV File.

Python: Writing into CSV files


 To saving data to a CSV file is done using the writer object provided by
the csv module.
 Let's see how to save Student Details to a CSV file.
 In the given example code, we first open the file for writing.
 The 'w' mode creates a file for us if it hasn't already been created.
 Next, we create a filewriter object that we use to add rows using
the writerow method.
 The writerow method takes a list of values as an argument, and then saves
them as one line in a CSV file.
 NOTE: Please note that writerow method accepts only a single argument
which we have given as a list here (notice the ‘[‘ and ‘]’ around the contents
to be written) .

import csv

with open('Student_Details.csv', 'w', newline=' ') as Myfile:

filewriter = csv.writer(Myfile, delimiter=',')

filewriter.writerow([‘RollNo’,'Name', 'Percentage', 'Remark'])


filewriter.writerow(['101','Arjun', '78',’Good’])
filewriter.writerow(['102’,'Amaan', '90',’V Good’])
filewriter.writerow([‘103’,'Vinod', '60',’Average’])
filewriter.writerow(['104',‘Dev’, '92',’Excellent’])
print("Data Saved in file Student_Details......")

Page 3 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
: File
Writing into CSV using loop: Handling
import csv

with open('csvfile.csv','w',newline='') as csvf:

writecsv=csv.writer(csvf,delimiter=',')

choice='y'

while choice.lower()=='y':

rl=int(input("Enter Roll No."))

n=input("Enter Name")

p=float(input("Enter Percentage"))

r=input("Enter Remarks")

writecsv.writerow([rl,n,p,r])

print(" Data saved in Student Details file..")

choice=input("Want add more record(y/n).....")

Python: Reading from CSV files

The csv.reader() method returns a reader object which iterates over lines in the
given CSV file.

Step 1: You have to imports the csv package so that you can use the methods
provided by it for easy csv I/O.

Step 2: opens the file student_Details in read mode and a file object called
fileobject, which points to the file contents.

Step 3: csv.reader is the object which iterates over the lines of the CSV file through
the File object readcsv.
Page 4 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
Example: : File Handling
import csv

with open('Student_Details.csv','w',newline='') as fileobject:

readcsv=csv.reader(fileobject)

for i in readcsv:

print(i)

Example: We will show how to pull out specific data from the spreadsheet and save
it to a list variable:

import csv
with open('Student_Details.csv') as csvf:
readCSV = csv.reader(csvf, delimiter=',')
RollNos = []
Remarks = []
for row in readCSV:
Rem = row[3]
Roll = row[0]

RollNos.append(Rem)
Remarks.append(Roll)
print(RollNos)
print(Remarks)

Page 5 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
Appending to CSV files : File Handling
Suppose we want to add a few lines to the “Student_Details.csv” file. The Append
mode ‘a’ can be of help. The below code appends rows to the existing
“Student_Details.csv” file:
import csv

with open('Student_Details.csv’,'a',newline='') as csvfile:

writecsv=csv.writer(csvfile,delimiter=',')

choice='y'

while choice.lower()=='y':

rl=int(input("Enter Roll No."))

n=input("Enter Name")

p=float(input("Enter Percentage"))

r=input("Enter Remarks")

writecsv.writerow([rl,n,p,r])

print(" Data saved in Student Details file..")

choice=input("Want add more record(y/n).....")

Page 6 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
Copy data from one file:toFile
anotherHandling
import csv

with open('copyout.csv' ,'w') as outFile:

fileWriter = csv.writer(outFile)

with open('Student_Details.csv','r') as inFile:

fileReader = csv.reader(inFile)

for row in fileReader:

fileWriter.writerow(row)

In the above code, first we open the file (in write mode) to which we want to copy
the contents, i.e. destination file (copyout.csv). Then, we create the writer object.
Further, we open the file (in read mode) from which we need to copy the contents
from, i.e. the source file (Student_Details.csv).

Page 7 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
Searching Record in CSV: file
File Handling
(Search By Roll number)
import csv

#input Roll number you want to search

number = input('Enter number to find: ‘)

#read csv, and split on "," the line

with open('Student_Details.csv') as f:

csv_file = csv.reader(f, delimiter=",")

#loop through csv list

for row in csv_file:

#if current rows index value (here 0) is equal to input, print that row

if number ==row[0]:

print (row)

OUTPUT:
Enter number to find: 103

['103', 'Vinod', '60', 'Average']

Page 8 of 9
Unit I: Computational Thinking and Programming - 2

Chapter-8
: File
Deleting record from CSV Handling
file by field value
For deleting the particular row from CSV file.

 read the csv file in memory as a list,


 then edit that list, and
 then write it back to the csv file.

Example:
import csv
lines = list()

rno= input("Please enter a student's roll no to be deleted.")

with open('Student_Details.csv', 'r') as readFile:

reader = csv.reader(readFile)

for row in reader:

lines.append(row)

for field in row:

if field == rno:

lines.remove(row)

with open('Student_Details.csv', 'w', newline='') as writeFile:

writer = csv.writer(writeFile, delimiter=',')

writer.writerows(lines)

with open('Student_Details.csv', 'r') as rFile:

readf = csv.reader(rFile)

for i in readf:

print(i)
Page 9 of 9

You might also like