0% found this document useful (0 votes)
8 views139 pages

Orientation - File Handling (Autosaved)

The document outlines a capacity building program on file handling for senior secondary teachers, focusing on the importance and types of files, including text and binary files. It covers operations such as reading, writing, and manipulating files in Python, as well as the use of buffers and file paths. Additionally, it provides examples of file operations and coding practices for managing files effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views139 pages

Orientation - File Handling (Autosaved)

The document outlines a capacity building program on file handling for senior secondary teachers, focusing on the importance and types of files, including text and binary files. It covers operations such as reading, writing, and manipulating files in Python, as well as the use of buffers and file paths. Additionally, it provides examples of file operations and coding practices for managing files effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 139

REGIONAL TRAINING CENTRE

DAV INSTITUTIONS, ODISHA ZONE-I


CAPACITY BUILDING PROGRAMME FOR SENIOR SECONARY TEACHERS
SESSION: 2020-21

Topic: FILE HANDLING

BY
MRS. GEETANJALI HOTA
Prepared by SCIENCE
PGT COMPUTER Geetanjali Hota
PGT.
DAV PUBLIC Computer
SCHOOL, Science
POKHARIPUT, , DAV PKT
BHUBANESWAR
Learning Objectives ::
• Need of Files
• Types of Files
• Text File Vs Binary File
• Read & Write operations on both types of file
• Random FilePrepared
Operation by Geetanjali Hota
PGT. Computer Science , DAV PKT
• Use of pickle module
• Reading & Writing CSV files
• Text and Binary File manipulations
• Assignment Questions .
Need of Files
Files are named locations on disk to store
related information. They are used to
permanently store data in a non-volatile
memory (e.g. hard disk).

Can also referred as bunch of bytes stored on


some storage device

1.Importance of File Handling In Python


When we want to read from or write to a file,
we need to open it first. When we are done, it
needs to be closed so that the resources that
are tied with the file are freed.
Buffers
• A buffer is a “special work area”
that holds data as the computer
transfers them to/from memory.

• The physical requirements of the


devices can deliver more data for
input than a program can use at any
one time. The buffer handles the
overflow data until a program can
use it.

• Moreover, the buffer also holds data


until it is efficient to write that data
to the storage device for output.
Buffers
• A buffer is a “special work area” that holds data as the
computer transfers them to/from memory.

• The physical requirements of the devices can deliver more


data for input than a program can use at any one time. The
buffer handles the overflow data until a program can use it.

• Moreover, the buffer also holds data until it is efficient to


write that data to the storage device for output.
❖There are two types of files in Python
Tip
They are:

* Binary file
* Text file
FILE PATHS
When you access a file on an operating system, a file path is
required. The file path is a string that represents the location of a
file. It’s broken up into three major parts:
Tip

Folder Path: the file folder location on the file system A file path is also
where subsequent folders are separated by a forward called a pathname.
slash / (Unix) or backslash \ (Windows)

File Name: The actual name of the file

Extension: the end of the file path pre-pended with a period (.)
used to indicate the file type
Text files
Its a sequential characters divided into lines.
– Each line terminates with the newline character (\n).

Example:
Web standards: html, XML, CSS, JSON etc.

Source code: c, app, nsist
js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Binary files
It consists of data values such as integers, floats
or complex data types, “using their memory
representation.”
Example:
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
1.How newlines (\n) are stored ?
Analyzing with 2. How end-of-file is indicated?
3 features 3. How datas are stored in
the file?
First feature
Carriage Return( \r)
• In text mode, a newline character is converted moves the cursor to
into the carriage return-linefeed combination the beginning of the
before being written to disk. line without advancing
to the next line
• Likewise, the carriage return-linefeed combination on the
disk is converted back into a newline when the file is read
by a Python program.
• However, if a file is opened in binary mode, as opposed to
text mode, these conversions do not take place. Line Feed ( \n) moves
• In binary mode, each end of line is signified by a carriage the cursor down to the
next line without
return-linefeed combination and is counted as two
returning to the
characters in binary mode. beginning of the line

End of Line (EOL) is actually two ASCII


characters and is a combination of the \r
and \n characters

10
Second Feature

• In text mode, a special character EOF whose ASCII value is 26 is


inserted after the last character in the file to mark the end of file.
• However, there is no such special character present in the binary mode
files to mark the end of file.

• The binary mode files keep track of the end of file from the number of
characters present in the directory entry of the file.

11
Third Feature
• In text mode, the text and numbers are stored as string of
characters such that the number 45678 will occupy 5 bytes
(1 byte/character).

• Similarly 45678.56 occupies 7 bytes on disk in text mode.

• However, in binary mode the numbers are stored in the same


way as they are stored in RAM so that the number 45678
occupies only 2 bytes and 4576.36 occupies only 4 bytes on
disk in binary mode.

Ms. Geetanjali Hota 12


PGT. DAV Public School, Bhubaneswar
FILE PATHS
An absolute file path describes how to access a
given file or directory, starting from the root of
the file system.
Tip
Relative file paths is the path to some file with respect to
your current working directory (PWD) .It is notated by a
leading forward slash.

Example:-
1.If remaining in the current folder i.e Jono I want to access
cory -> ..\cory
2.If lib file to be accessd from the current folder Usr -> .\lib
file
3.If Remaining in the current folder usr work file to be
accessed which is under Jono-> ..\HOME\JONO\work file
Basic operations performed on a data file are:

1. Naming a file

2. Opening a file

3. Reading data from the file

4. Writing data in to the file

1. Closing a file
Steps to process a file

● 1. Determine the type of file usage


Reading- File to memory link
Writing-> Memory to file link
● 2. Open the file and assign its reference to a file
object or file –handle
Assign open() to file handle/file object to perform the
operation
● 3. Now process as required.
● 4. Close the file
As the last lap of data remains in buffer and is not
pushed on to disk until a close() is performed .
❖ Opening a File Opening a File
File_object = open(r"File_Name", "Access_Mode")

File_object = open(r"File_Name", "Access_Mode")


File handler is like a cursor, which
defines from where the data has to
File handler is like a cursor, be
which
read defines
or writtenfrom where
in the file
the data has to be read or written in the file
.
byte by byte or line by lineAccess
. modes govern the type of
operations possible in the opened
file of
Access modes govern the type
operations possible in the opened file

The file should exist in the same directory as the Python script, otherwise
The file should exist in the sameofdirectory
full address asbewritten.
the file should the Python script,
otherwise full address of the file should bewritten.
❖ The with statement Opening a File
File_object = open(r"File_Name", "Access_Mode")

with expression as variableFile


: handler is like a cursor, which
defines from where the data has to
>>> with open('poem.txt') as f: be read or written in the file
print(f.read()) # read the entire. file ...
Tip of
Access modes govern the type
operations possible in the opened
file The statements inside
It allows us to automatically close the file once we are the with statement must
done working with it. Its syntax is as follows: be indented equally just
like the for loop,

The file should exist in the same directory as the Python script, otherwise
otherwise Syntax
full address of the file should bewritten. Error exception will be
raised.
ACCESS MODES Opening a File
Tip
Example 1:

fo =
open(“C://Python//test.txt”,
“r+”)
. Example 2:

fo =
open(“C://Python//img.bmp”,
“rb+”)
Opening a File
1 Myfile=open(‘PKT.txt’) File
Object

2 Myfile=open(‘PKT.txt’,’r’)

3 Myfile=open(‘c:\\temp\\data.txt’,’r’)

4 Myfile=open(r’c:\temp\data.txt’, ‘r’)
Closing a File

Myfile.close()

File
Object Because if we don’t call the close function after the write
method then whatever data we have written to a file will
not be saved into the file.
File Objects and its Properties
Reading from a File
str=myfile.read(30)
# Next read() reads the next 30 characters from the last read
F=open(r”E:/poem.txt”,”r”).read(30)
# Reads one line from the file
F=open(“poem.txt”,”r”).readline()
# reads all line from the file
F=open(“poem.txt”,”r”).readlines()
# Entire file will be read
F=open(“poem.txt”,”r”).read()
Reading Data From File
In order to read a file in python, we must open the file in read mode.
There are three ways in which we can read the files in python.
Here, n is the number of bytes to be read.

read(n)
readline(n)
readlines()
Read file in Python

Reading File using my_file.read(5) method

output - Reading File using my_file.read(5) method

.
# Python code to illustrate read() mode character wise

Example-1
Read file in Python Reading File using my_file.read(5) method

output - Reading File using my_file.read(5) method

.
# Reading the content of the File
Example 2:

my_file = open(“C:/Documents/Python/test.txt”, “r”)


print(my_file.read())

Output:
Hello World
Hello Python
Good Morning
How are You

Here we have not provided any argument inside the read()


function. Hence it will read all the content present inside the file.
More coding on Read()
#
Reading the specific characters from the file
Readline(n)
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))

Output:
He
This function returns the first 2 characters of the next line.
Example of Reading File using readline(2) method

Ouput of Reading File using readline(2) method


# Reading the content line by line from the file

Readline()
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())

Output:
Hello World
(Using this function we can read the content of the file on a line by line basis.)
Example of Reading File using readline() method

Output - Reading File using readline() method


# Reading the content line by line from the file

Readline()
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())

Output:
Hello World
(Using this function we can read the content of the file on a line by line basis.)
Example of Reading File using readline() method

Output - Reading File using readline() method


More coding on Readline()
More coding on Readline()
Python program to copy one file to other
with open("C:/Users/Geetanjali/Desktop/demofile.txt") as f:
with open("out1.txt", "w") as f1:
for line in f:
f1.write(line)
Alternative method

import shutil
original = r'C:/Users/Geetanjali/demofile.txt'
target=r'C:/Users/Geetanjali/demofile1.txt'
shutil.copyfile(original, target)
#Reading all the lines including the newline characters.
Readlines()
Example 5:
write()_method with next line - Output

Reading_File_using_readlines()_method

Reading_File_using_readlines()_method_output
# Reading a specific line from a File
● In the following example, we are trying to read only the 4th line
from the ‘test.txt’ file using
Reading specific line from a file

Reading specific line from a file - Output


More coding on Readlines()
Write to File

We have two methods for writing data into a file as shown


below.

write(string)
writelines(list)
Example 1:

The above code writes the String


‘Hello World’ into the ‘test.txt’ file.
Before writing data to a test.txt file:
Python - Before writing data to test file Python - Example for write()_method

write()_method - Output
Example 2: write()

The first line will be ‘Hello World’ and as we have mentioned \n


character, the cursor will move to the next line of the file and then
write ‘Hello Python’.

Remember if we don’t mention \n character, then the data will be


written continuously in the text file like ‘Hello WorldHelloPython’
write()_method with next line

write()_method with next line - Output


Example 3: writelines()

● The above code writes a list of data into the


‘test.txt’ file simultaneously.
Example for writelines()_method

● .
writelines()_method - Output
Appending data to File
● To append data into a file we must open the file in ‘a+’ mode so that we will have
access to both the append as well as write modes.
Example 1:
● This code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file
Example - Appending Data to File

Appending Data to File - Output

Example 2:
The above code appends the string ‘Guava’ at the end ofAppending
the ‘test.txt’ file
data file at a new line in a new line.
- Output
Appending data file at a new line
More Coding on write()
More Coding on writelines()
● Example-3
The code appends a list of data into a ‘test.txt’ file.

Append a list of data

Append a list of data - output


Example: use of split()
# Python code to illustrate split() function
with open("C:/Users/Desktop/file1.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word )
#File name according to user input
a=input('Please enter the file with path')
f=open(a,'w')
f.write("New File Created")
f.close()
f=open(a,'r')
print(f.read())
f.close()
Example: Appending and writing to a File
#Create a new empty file called "myfile.txt":
f = open("C:/Users/myfile.txt", "x") #gives error if the file already
exists
#Create a new file if it does not exist:
f = open("myfile.txt", "w")

# Python code to illustrate with() alongwith write()


with open("C:/Users/file1.txt", "w") as f:
f.write("Hi!!!! Every one....")
f.write('Welcome here ....')
f=open('file1.txt','r')
print (f.read())
Example: Write & Read data from a File
# Program to show various ways to read data from a file.
L = ["This is India \n", "This is Odisha \n", "This is Silicon \n"]

# Creating a file
with open("C:/Users/myfile2.txt", "w") as file1:
# Writing data to a file
file1.write("Hi!!!!! \n")
file1.writelines(L)
file1.close() # to change file access modes

with open(" C:/Users/myfile2.txt", "r+") as file1: # Reading form a file


print(file1.read())
#Remove the file
"demofile.txt": import os
os.remove("demofile.txt")

#Check if file exists, then delete it:


import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
tell()
It returns the current position of the file
handler

Syntax:
fileObject.tell()

Dr. Pradyumna Kumar Tripathy,


Associate Professor, Silicon Institute of Technology, Bhubaneswar
● In Python, seek() function is used to change the position of the File
Handle to a given specific position. File handle is like a cursor, which
defines from where the data has to be read or written in the file.
Example: Reading from a File
#Another way of Reading the content one line at a time
f = open("C:/Users/demofile.txt", "r")
p=f.tell()
print('File Pointer at:',p)
f.seek(10)
p=f.tell()
print('File Pointer at:',p)
for x in f:
print(x)
print ('End of loop')
seek()
Moves the file handler to the desired
location
Syntax:
fileObject.seek(offset, whence)
offset:position of the read/write pointer within the file
whence:optional and defaults to 0
1 Absolute file positioning
2 seek relative to the current position
3 seek relative to the end of File
Example: Use of seek( )
#Use of seek()
f = open('C:/workfile', 'wb+')
f.write(b'0123456789abcdef')
f.close()
f = open('C:/workfile', 'rb+')
f.seek(5) # Go to the 6th byte in the file #’5’
print(f.read()) #b'56789abcdef'
f.seek(5)
print(f.read(1)) # b'5'
f.seek(-3, 2) # Go to the 3rd byte before the end
print(f.read()) #def
f.seek(-3, 2)
print(f.read(1)) #b'd'
rename() method:
.

Syntax:
os.rename(current_file_name, new_file_name)
Example 1:

import os
os.rename(“test.txt”, “test1.txt”)

Here ‘test.txt’ is the current file name and ‘test1.txt’ is the


new file name.

You can specify the location as well as shown in the below example.
Example 2:
import os
os.rename(“C:/Documents/Python/test.txt”,
“C:/Documents/Python/test1.txt”)
Python - Renaming a file

Before Renaming the file:


Python - Before renaming the file

After executing the above program


Python - After renaming the file
remove() method:
.remove() method:
We use the remove() method to delete the file by supplying
the file name or the file location that you want to delete.
Syntax: os.remove(file_name)
Example 1:
import os
os.remove(“test.txt”)
Here ‘test.txt’ is the file that you want to remove.
Similarly, we can pass the file location as well to the arguments
as shown in the below example

Example 2:
import os
os.remove(“C:/Documents/Python/test.txt”)
Standard Input, Output, and Error

● The interpreter provides three standard file objects, known


as standard input, standard output, and standard error, which are
available in the sys module as sys.stdin, sys.stdout, and sys.stderr,
respectively.
● stdin is a file object corresponding to the stream of input characters
supplied to the interpreter.
● stdout is the file object that receives output produced by print.
● stderr is a file that receives error messages.
● More often than not, stdin is mapped to the user’s keyboard,
whereas stdout and stderr produce text onscreen.
Standard Input, Output, and Error

● Standard input – This is the file-handle that a


user program reads to get information from the
user. We give input to the standard input
(stdin).
● Standard output – The user program writes
normal information to this file-handle. The
output is returned via the Standard output
(stdout).
● Standard error – The user program writes error
information to this file-handle. Errors are
returned via the Standard error (stderr).
Example code of stdout and stderr
Examplary programs on stdin, stdout and stderr
flush()
It forces the writing of the data on the disc still pending in output buffer

f=open("C:/Users/Geetanjali/Desktop/out.dat","w+")
f.write("The output is \n")
f.write("My" + "work status"+ "is :")
f.flush()
s='OK'
f.write('')
f.write(s)
f.write('\n')
f.write("Finally Over \n")
f.flush()
f.close()
# Removing EOL character
Fn=open("C:/Users/Desktop/TEST.txt","r")
line=Fn.readline()
line=line.rstrip('\n')
print(line)
# Removing White Spaces
Fn=open("C:/Users/Desktop/TEST.txt","r") line=Fn.readline()
line=line.lstrip()
line=line.rstrip()
print(len(line))
BINARY FILE MODE
Advantages of Binary files
Binary file handling
Binary files are faster than text file in processing

The content of binary files can not be copied using text


editors

They take less space compared to text files

The creation of binary files comes first compared to text


files.

We can generate Text files using any text editor but the same
is not true for binary files.

Prepared by Geetanjali Hota


Binary file handling

Prepared by Geetanjali Hota


Pickle Module(Write/Read)
File handling- Binary File (Pickle)- CREATE
Pickle module
import pickle Pickling is a way to convert python object into a character stream(
list1 = [] binary)
while True:
roll= input("Enter student Roll No:")
sname= input("Enter student Name :")
student={"roll": roll, "name": sname}
list1.append(student)
choice = input("Want to add more record(y/n) :")
if(choice == 'n'):
break

file = open("student.dat", "wb")


pickle.dump(list1, file) Pickle.dump(object, file )
file.close() To write the object into the opend file
File Handling – Binary File(pickle) -READ
import pickle Object = pickle.load(file)
To read the object from opened binary file
file = open("student.dat", "rb") Enter student Roll No:2
list = pickle.load(file) Enter student Name:Asim Prasad
print(list) Want to add more record(y/n):y
file.close() Enter student Roll No:4
Enter student Name:Sovan Mohanty
Want to add more record(y/n):n
OR
for x in list: [{'roll': '2', 'name': 'Asim
print(x['roll'],x['name']) Prasad'}, {'roll': '4', 'name':
'Sovan Mohanty'}]

10 amit
20 ramji
Python Program to Write and Read a binary
file
import pickle
output_file = open("myfile.dat","wb")
myint = 42
mystring = "Hello, world!"
mylist = ["dog", "cat",
"lizard"]
mydict = { "name": "Bob", "job": "Astronaut" }

pickle.dump(myint, output_file)
pickle.dump(mystring,
output_file)
pickle.dump(mylist, output_file)
pickle.dump(mydict, output_file)
Program to Write and Read a binary file
import pickle
input_file = open(“myfile.dat","rb")
myint = pickle.load(input_file)
mystring = pickle.load(input_file)
mylist = pickle.load(input_file)
mydict = pickle.load(input_file)

print("myint =",myint)
print("mystring =",mystring)
print("mylist = ",mylist)
print("mydict = ",mydict)
APPENDING RECORDS
PROGRAM OUTPUT
APPENDING (Read)/PROGRAM OUTPUT
PROGRAM TO SEARCH A REORD
Deleting an element from Binary file
Printing the output(Deletion)
PROGRAM TO UPDATE A RECORD
File Handling – Binary File( pickle) - SEARCH 91

import pickle Name to search :rakesh


name = input('Name to search :') Not found
file = open("student.dat", "rb")
list1 = pickle.load(file) Name to search :ramji
file.close() Found in binary file

found = 0
for x in list1:
if name in x['name']:
found = 1
print("Found in binary file" if found == 1 else "Not found")

NOTE: Pay close attention on the if else used for printing final result
File handling – Binary File(pickle) - Update 92

import pickle
Mode “rb+” is used to read
name = input('Name to update :') and write at the same time.
file = open("student.dat", "rb+")
list = pickle.load(file)

found = 0 Name to update :ramji


lst = [] Enter new name Shree Ramji
for x in list:
if name in x['name']:
Record Updated
found = 1
x['name'] = input('Enter new name ')
lst.append(x)

if(found == 1): Bring writing head at the


file.seek(0)
pickle.dump(lst, file) beginning of file
print("Record Updated")
else:
print('Name does not exist')

file.close()
File handling – CSV File
95

CSV( Comma separated value) file are used to transfer data between the
applications. These files can be generated using any Text Editor, Excel and any
other supported software.
Sample CSV file generated using Excel First row contains the
Rollno,name,class,stream,agg,percenrage,result header
1,ramji,12B,SCIENCE,484,96.8,PASS
2,anuj,11A,COMM,452,90.4,PASS
3,ujjwal,12C,HUMAN,385,77,PASS
4,shlok,11B,SCIENCE,490,98,PASS
5,nipun,11A,COMM,347,69.4,PASS Single record
6,arushi,12C,COMM,456,91.2,PASS
7,ayushi,11B,HUMAN,345,69,PASS
8,sehaj,12A,SCIENCE,421,84.2,PASS
9,swarnima,12A,SCIENCE,345,69,PASS
10,harsh,11C,HUMAN,455,91,PASS
csv files
File handling – CSV File(Writer)-WRITE 99

import csv Separate header and


header =["ID","name","Price","Qty"]
records =[ records for the sake of
["102","LG Monitor","6500","20"], understanding only
["103","KeyBoard","1350","156"],
["105","Hp Mouse","650","120"],
["106","Speaker","1670","136"]
ID,name,Price,Qty
]
102,LG Monitor,6500,20
f = open("stock.csv","w")
csvwriter = csv.writer(f) 103,KeyBoard,1350,156
csvwriter.writerow(header)
csvwriter.writerows(records) 105,Hp Mouse,650,120
f.close()
print("Check your file now....") 106,Speaker,1670,136

csvwriter = csv.writer(f,lineterminator=“\n”)
Note: Since “\n\r” is default line feed in. To avoid an Extra white line in your output, add line
terminator while opening a file for writing.
File handling – CSV (Writer)-WRITE 100

import csv
records =[
["ID","name","Price","Qty"],
["102","LG Monitor","6500","20"],
["103","KeyBoard","1350","156"], Header and Records merged in
a single List
["105","Hp Mouse","650","120"],
["106","Speaker","1670","136"]
]
f = open("stock.csv","w")
csvwriter = csv.writer(f,lineterminator=“\n”)
csvwriter.writerow(header) # deleted this line
csvwriter.writerows(records) ID,name,Price,Qty
f.close() 102,LG Monitor,6500,20
print("Check your file now....") 103,KeyBoard,1350,156
105,Hp Mouse,650,120
106,Speaker,1670,136
File handling – CSV( Reader) - READ 101

import csv
f = open(r"C:\Users\geetanjali\Desktop\student.csv", "r")
data = csv.reader(f)
It return the CSV object in “data”
for record in data:
print(record)
f.close()
['Rollno', 'name', 'class', 'stream', 'agg', 'percenrage', 'result']
['1', 'ramji', '12B', 'SCIENCE', '484', '96.8', 'PASS']
['2', 'anuj', '11A', 'COMM', '452', '90.4', 'PASS']
['3', 'ujjwal', '12C', 'HUMAN', '385', '77', 'PASS']
['4', 'shlok', '11B', 'SCIENCE', '490', '98', 'PASS']
['5', 'nipun', '11A', 'COMM', '347', '69.4', 'PASS']
……..
['10', 'harsh', '11C', 'HUMAN', '455', '91', 'PASS']
File Handling – (CSV)- DictWriter - WRITE 102

rollno,name,stream,fees
import csv 12,surendra,Humanities,2356
13,Ashok,Humanities,2356
headers =['rollno','name','stream','fees'] 15,Nipun,Humanities,2356
records = [ 22,Ayush Negi,Science,2356
{'fees': 2356, 'rollno': 12, 'name': 'surendra', 'stream': 'Humanities’},
{'rollno': 13, 'stream': 'Humanities', 'fees': 2356,'name': 'Ashok’},
{'rollno':15,'name':'Nipun','stream':'Humanities','fees':2356},
{'rollno': 22, 'name': 'Ayush Negi', 'fees': 2356,'stream': 'Science’},
]

f = open("student.csv", "w")
writer = csv.DictWriter(f, fieldnames = headers, lineterminator='\n')
writer.writeheader()
writer.writerows(records) Fieldnames is compulsory
f.close()
print("Check your file now....“)
Writeheader() method is compulsory
File handling - CSV(DictReader)- READ 103

import csv
f = open(r"C:\Users\geetanjali\Desktop\student.csv", "r")
data = csv.DictReader(f)
for record in data:
print(dict(record))
f.close()

OrderedDict([('Rollno', '1'), ('name', 'ramji'), ('class', '12B'), ('stream', 'SCIENCE'), ('agg', '484'), ('percenrage', '96.8'), ('result',
'PASS')])
OrderedDict([('Rollno', '2'), ('name', 'anuj'), ('class', '11A'), ('stream', 'COMM'), ('agg', '452'), ('percenrage', '90.4'), ('result', 'PASS')])
OrderedDict([('Rollno', '3'), ('name', 'ujjwal'), ('class', '12C'), ('stream', 'HUMAN'), ('agg', '385'), ('percenrage', '77'), ('result', 'PASS')])
OrderedDict([('Rollno', '4'), ('name', 'shlok'), ('class', '11B'), ('stream', 'SCIENCE'), ('agg', '490'), ('percenrage', '98'), ('result', 'PASS')])
OrderedDict([('Rollno', '5'), ('name', 'nipun'), ('class', '11A'), ('stream', 'COMM'), ('agg', '347'), ('percenrage', '69.4'), ('result', 'PASS')])
OrderedDict([('Rollno', '8'), ('name', 'sehaj'), ('class', '12A'), ('stream', 'SCIENCE'), ('agg', '421'), ('percenrage', '84.2'), ('ressult',
'PASS')])ult', 'PASS')]) ', 'PASS')])
OrderedDict([('Rollno', '9'), ('name', 'swarnima'), ('class', '12A'), ('stream', 'SCIENCE'), ('agg', '345'), ('percenrage', '69'), ('result',
'PASS')])
OrderedDict([('Rollno', '10'), ('name', 'harsh'), ('class', '11C'), ('stream', 'HUMAN'), ('agg', '455'), ('percenrage', '91'), ('result', 'PASS')])
DictReader() method read all the CSV data in Ordered Dictionary format.
File handling - CSV(DictReader)- READ 104

import csv
f = open(r"C:\Users\geetanjali\Desktop\student.csv", "r")
data = csv.DictReader(f) DictReader() method is used to read data as a
for record in data: Dictionary
print(dict(record))
f.close()

{'Rollno': '1', 'name': 'ramji', 'class': '12B', 'stream': 'SCIENCE', 'agg': '484', 'percenrage': '96.8', 'result': 'PASS'}
{'Rollno': '2', 'name': 'anuj', 'class': '11A', 'stream': 'COMM', 'agg': '452', 'percenrage': '90.4', 'result': 'PASS'}
{'Rollno': '3', 'name': 'ujjwal', 'class': '12C', 'stream': 'HUMAN', 'agg': '385', 'percenrage': '77', 'result': 'PASS'}
{'Rollno': '4', 'name': 'shlok', 'class': '11B', 'stream': 'SCIENCE', 'agg': '490', 'percenrage': '98', 'result': 'PASS'}
{'Rollno': '5', 'name': 'nipun', 'class': '11A', 'stream': 'COMM', 'agg': '347', 'percenrage': '69.4', 'result': 'PASS'}
…..
{'Rollno': '10', 'name': 'harsh', 'class': '11C', 'stream': 'HUMAN', 'agg': '455', 'percenrage': '91', 'result': 'PASS'}

Ordered Dictionary is not in our syllabus thus we change them into normal dictionary using
dict(record)
Sample code (csv file writing)
csv file
Output Structure
Sample Code(csv file Reading)
Sample code for Searching)
Searching a record in csv file
File handling –CSV ( Search Record) 111

import csv
name = input('Name to Search :')
Name to Search :Ashok
Ashok found in CSV file..
file = open('student.csv','r')
reader = csv.DictReader(file)
found =0
for x in reader: Name to Search :nipun
x = dict(x) nipun not found....
if(x['name']==name):
print(name,' found in CSV file..')
found =1
file.close()

if(found == 0):
print(name, ' not found....')
File Handling- CSV ( Delete Record ) 112

import csv
name = input('Name to delete :')
records=[]
found =0
file = open("student.csv","r")
reader = csv.DictReader(file)
for record in reader:
record = dict(record)
if(record['name']!=name): Collect all record in a list excluding the matched one
records.append(dict(record))
else:
found =1
file.close() Headers are not the part of DictReader ()
# Remove the old file and create a new csv file
headers=['rollno','name','stream','fees']
file = open("student.csv","w")
writer = csv.DictWriter(file,fieldnames =headers, lineterminator ='\n')
writer.writeheader()
writer.writerows(records)
file.close()
if(found==0):
print(name, " does not exists") Write all the collected record in the same CSV file
else:
print(name," deleted successfully")
File Handling (CSV) UPDATE RECORD 113

import csv
name = input('Name to Update :')
records = []
found = 0
file = open("student.csv", "r")
reader = csv.DictReader(file) Ask for a new Name when Name match,
for record in reader:
record = dict(record) append the list in both cases
if(record['name'] == name):
record = dict(record)
record['name'] =input('New Name:')
records.append(record)
found=1
else:
records.append(dict(record))
file.close()
headers = ['rollno', 'name', 'stream', 'fees']
file = open("student.csv", "w") # Remove the old file and create a new csv file
writer = csv.DictWriter(file, fieldnames=headers, lineterminator='\n')
writer.writeheader()
writer.writerows(records)
file.close()
if(found == 0):
print(name, " does not exists")
else:
print(name, " updated successfully")
SAMPLE BOARD QUESTIONS ??

WAP to create a file to hold some data ,separated as lines


SAMPLE BOARD QUESTIONS ??
WAP to create a file to hold some data ,separated as lines

Fileout=open(“student.txt”, ”w”)
for i in range(3):
name=input(“enter name of student:”)
Fileout.write(name)
Fileout.write(‘\n’)
Fileout.close()

Sample run – Enter name of the student: sourav


Enter name of the student:andhya
Enter name of the student:Sohan
program to find out total number of lines that start with alphabet ‘T’
program to find out total number of lines that start with alphabet ‘T’

file = open(r"abcd.txt",'r')
count=0;
for line in file.readlines():
if line[0]=='T':
count+=1
file.close()
print("Total lines that start with alphabet 'T' :",count)
program to find out the total number of words in any given test file
program to find out the total number of words in any given test file

file = open(r"abcd.txt")
words = lines = 0
for line in file.readlines():
lines += 1
words += len(line.split())
file.close()
print("Total Words in this File :", words)
print("Total Lines in this File :", lines)
WAP to print just the last line of a text file “data.txt”
WAP to print just the last line of a text file “data.txt”

Fin=open(“data.txt”, “r”)
Linelst=Fin.readlines()
print(“Last line=“,Linelst[-1])
WAP to read the text file and prints only the numbers or digits from the file.
WAP to read the text file and prints only the numbers or digits
from the file.
F=open(“an.txt”,”r”)
for line in F :
words=line.split()
for i in words :
for letter in i:
if(letter.isdigit())
print(letter)
WAP that copies a text file “source.txt” onto “target.txt” barring
the lines starting with a “@” sign
WAP that copies a text file “source.txt” onto “target.txt”
barring the lines starting with a “@” sign

def Filter(oldfile, newfile):


fin=open(oldfile,”r”)
fout=open(newfile,”w”)
while True :
text=fin.readline()
if len(text)==0:
break
if text[0]==“@”:
continue
fout.write(text)
fin.close()
fout.close()
Filter(“source.txt”, “target.txt”)
PROGRAM-7
SOURCE CODE
PROGRAM-8
SOURCE CODE
PROGRAM-9
PROGRAM-10
PROGRAM-11
PROGRAM-12
PROGRAM-13
PROGRAM-14
PROGRAM-15
PROGRAM-16
PROGRAM-17

You might also like