0% found this document useful (0 votes)
3 views58 pages

Class 12 File Handling

Uploaded by

gz47xdnpvg
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)
3 views58 pages

Class 12 File Handling

Uploaded by

gz47xdnpvg
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/ 58

NCERT

What is File?

A file is a named location on a secondary storage media where data are permanently
stored for later access.

Computers store every file as a collection of 0s and 1s i.e., in binary form. Therefore,
every file is basically just a series of bytes stored one after the other.
There are mainly two types of data files

Text Files Binary Files

A text file consists of human readable characters, which can be opened by any text editor.
On the other hand, binary files are made up of non-human readable characters and symbols,
which require specific programs to access its contents.
Text Files
▪ A text file can be understood as a sequence of characters consisting of alphabets,
numbers and other special symbols.

▪ Files with extensions like .txt, .py, .csv, etc. are some examples of text files.

▪ In computer internally, they are stored in sequence of bytes consisting of 0s and 1s.

▪ A text file stores information in the form of a stream of ASCII or Unicode characters.

▪ So, while opening a text file, the text editor translates each ASCII value and shows us the
equivalent character that is readable by the human being.

▪ Each line of a text file is terminated by a special character, called the End of Line (EOL).

▪ For example, the default EOL character in Python is the newline (\n).
Binary Files
• Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these bytes do
not represent the ASCII values of characters.

• Rather, they represent the actual content such as image, audio, video, compressed versions of
other files, executable files, etc.

• These files are not human readable. Thus, trying to open a binary file using a text editor will
show some garbage values.

• Binary files are stored in a computer in a sequence of bytes. Even a single bit change can
corrupt the file and make it unreadable to the supporting application.
Opening a File
Opening a file :: To open a file in Python, we use the open() function.

The syntax of open() is as follows:

file_object= open(file_name)
OR
file_object= open(file_name, access_mode)

• access_mode : returns the access mode in which the file was opened.
• file_name : returns the name of the file.
Opening a File
Example:
f=open("demofile.txt","r")
print(f.read())

Open a file on a different location:


f=open("D:\\myfiles\\welcome.txt","r")
print(f.read())

NOTE: The file_name should be the name of the file that has to be opened. If the file is not in
the current working directory, then we need to specify the complete path of the file along with
its name.
Opening a File
File Access Modes

Text File Binary File Description Notes


Mode Mode
‘r’ ‘rb’ Read only Default Mode;File must exist already,otherwise python raises I/O error
‘w’ ’wb’ Write only If File does not exist,file is created.
If the file exists,python will over write the data in the file.
‘a’ ‘ab’ append If File does not exist,file is created.
If the file exists,the data in the file is retained and new data being written
will be appended to the end.
‘r+’ ‘rb+’ Read and write File must exists otherwise error is raised.
Both reading and writing operations can take place.
‘w+’ ‘wb+’ Write and read File is created if does not exist.
If file exists ,past data is over written.
‘a+’ ‘ab+’ Write and read File is created if does not exists.
If file exists,the data in the file is retained and new data appended to the
end.
Closing a File
Close Files

It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f=open("demofile.txt","r")
print(f.readline())
f.close()
Working With Text File
Reading from Text Files

❖read()
❖readline()
❖readlines()
Working With Text File

❖read()
By default the read() method returns the whole text, but you can also
specify how many characters(n) you want to return.

Return the read bytes in the form of string.

Example:
Return the 5 first characters of the file:
f=open("demofile.txt","r")
print(f.read(5))
Working With Text File

❖readline()

You can return one line by using the readline() method.


If n is specified reads at most n bytes.

Return the read bytes in the form of string ending with new line
character (\n).

Example:
Read one line of the file:
f=open("demofile.txt","r")
print(f.readline())
Working With Text File

❖readlines()
The method reads all the lines and returns the lines along with newline as a list of strings.

Example:
f=open(“demofile.txt", 'r')
print(f.readlines())
f.close()

O/P:-
• ['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']

• As shown in the above output, when we read a file using readlines() function, lines in the file
become members of a list, where each list element ends with a newline character (‘\n’).
Write a Text File
Write to an Existing File

To write to an existing file, you must add a parameter to the open()


function:
• "a" - Append - will append to the end of the file
• "w" - Write - will overwrite any existing content

After opening the file, we can use the following methods to write data in
the file.
❑write() - for writing a single string
❑writelines() - for writing a sequence of strings(list ,tuple etc)
Write a Text File
The write() method :

write() method takes a string as an argument and writes it to the text file.
Consider the following piece of code:
f=open("myfile.txt",'w')
f.write("Hey I have started using files in Python\n")
f.close()
If numeric data are to be written to a text file, the data need to be converted into string before
writing to the file.
For example:
f=open("myfile.txt",'w')
marks=58
f.write(str(marks))
f.close()
Write a Text File
The writelines() method :

This method is used to write multiple strings to a file.


We need to pass an iterable object like lists, tuple, etc. containing strings to
the writelines() method.

The following code explains the use of writelines().

f=open("myfile.txt",'w')
list = ["Hello everyone\n", "Writing multiline strings\n", "This is the third line"]
f.writelines(list)
f.close()
Random Access a File
1. seek( ) method 2. tell( ) method

1.seek( ):- This function is used to change the position of file


handler(file pointer) to a given specific position.

File pointer is like a cursor ,which define from where the data has
to be read or written in the file.
Syntax:-
f.seek(offset,from_what)
Random Access a File
1. seek( ) method
f.seek(offset,from_what)
Offset is a number specifying number of bytes
Reference_point(from_what) indicates the starting position of the file
object. It can have any of the following values:
0 - beginning of the file(By default)
1 - current position of the file
2 - end of file

For example, the statement f.seek(5,0) will position the file object at 5th
byte position from the beginning of the file.
Random Access a File
2. tell( ) method

This function returns an integer that specifies the current position


of the file pointer in the file. The position so specified is the byte
position from the beginning of the file till the current position of
the file object.

The syntax of using tell ( ) is:

file_object.tell()
File Handling
1. split() function
In case we want to display each word of a line separately as an element of a list, then
we can use split() function.
The following code demonstrates the use of split() function.

f=open("class12.txt",'r')
d=f.readlines() ['hello student\n', 'data science\n', 'Computer Science']
for line in d:
words=line.split()
print(words)
O/P:-
['hello', 'student']
['data', ‘science']
['Computer', 'Science']
In the output, each string is returned as elements of a list.
File Handling
2. splitlines( ) method

However, if splitlines() is used instead of split(), then each line is returned as element of a
list, as shown in the output below:
f=open("class12.txt",'r')
d=f.readlines() ['hello student\n', 'data science\n', 'Computer Science']
for line in d:
words=line.splitlines()
print(words)
O/P:-
['hello student']
['data science']
['Computer Science']
Text Files
1. Write a program to read a text file line by line and display each word separated by #.

['hello student\n', 'data science\n', 'Computer Science']

OUTPUT:
hello#student#
data#science#
Computer#Science#
Text Files
1. Write a program to read a text file line by line and display each word separated by #.

f=open(“class12.txt”, ‘r’)
d=f.readlines() ['hello student\n', 'data science\n', 'Computer Science']
for line in d:
words=line.split()
for w in words: ['hello', 'student']
['data', ‘science']
print(w,end= ‘#’) ['Computer', 'Science']
print()
f.close()

OUTPUT:
hello#student#
data#science#
Computer#Science#
Text Files
2. Write a program to display the number of lines in a text file.

['hello student\n', 'data science\n', 'Computer Science']

OUTPUT:
Number of lines in text file is=3
Text Files
2. Write a program to display the number of lines in a text file.

f=open(“class12.txt”, ‘r’)
data=f.readlines() ['hello student\n', 'data science\n', 'Computer Science']
Count=len(data)
print(“Number of lines in text file is=“,Count)
f.close()

OUTPUT:
Number of lines in text file is=3
Text Files
3. Write a method in python to read lines from a text file ‘class12.txt’ and display those lines
which are starting with an alphabet H.

['Hello student\n', 'Data science\n', 'High


level language\n', 'Computer science\n']

OUTPUT:
Hello student

High level language


Text Files
3. Write a method in python to read lines from a text file ‘class12.txt’ and display those lines
which are starting with an alphabet H.

def read():
f=open(“class12.txt”, ‘r’)
data=f.readlines() ['Hello student\n', 'Data science\n', 'High
for i in data: level language\n', 'Computer science\n']
if(i[0])==‘H’:
print(i)
read()

OUTPUT:
Hello student

High level language


Text Files
4. Write a method in python to count the number of lines from a text file ‘class12.txt’
which are starting with an alphabet H.

['Hello student\n', 'Data science\n', 'High level


language\n', 'Computer science\n']

OUTPUT:
Total no of lines starting with an alphabet H is=2
Text Files
4. Write a method in python to count the number of lines from a text file ‘class12.txt’
which are starting with an alphabet H.

def read():
f=open(“class12.txt”, ‘r’)
['Hello student\n', 'Data science\n', 'High level
data=f.readlines()
language\n', 'Computer science\n']
count=0
for i in data:
if(i[0])==‘H’:
count+=1
print(“Total no of lines starting with an alphabet H is=“,count)
read()

OUTPUT:
Total no of lines starting with an alphabet H is=2
Text Files
5. Write a program in python to count the number of characters from a text file ‘class12.txt’.

hello student
data science
computer science

OUTPUT:
No of characters=38
Text Files
5. Write a program in python to count the number of characters from a text file ‘class12.txt’.

f=open('class12.txt', 'r')
d=f.read() hello student
c=0 data science
for line in d: computer science
words=line.split()
for w in words:
c+=1;
print("No of characters=",c)
f.close()

OUTPUT:
No of characters=38
Text Files
6. Write a program in python to count the number of words from a text file ‘class12.txt’.

['hello student\n', 'data science\n', 'Computer Science']

OUTPUT:
No of words=6
Text Files
6. Write a program in python to count the number of words from a text file ‘class12.txt’.

f=open('class12.txt', 'r')
d=f.readlines() ['hello student\n', 'data science\n', 'Computer Science']
c=0
for line in d:
words=line.split() ['Hello', 'student']
for w in words:
c+=1;
print("No of words=",c)
['data', 'science']
f.close()
['computer', 'science']

OUTPUT:
No of words=6
Binary Files

❖Binary files are stored in terms of byte stream (0s and 1s).
❖These files are not human readable. Thus, trying to open a binary file using a text editor
will show some garbage values.
❖There is no delimiter for a new line .
❖These files can not be read and write directly.
❖These files are understood only by a computer or a machine.
❖These files are very easy and fast in working.

Example of Binary File


Binary Files

Pickle pickling
Module unpickling
Binary Files

Byte Streams
Python Objects Serialization 10111011101110
Pickling 11000110011010
11100001110001
pickle.dump() 00011100010101
10101010101010
01000111010101
00001111100011
10101110011100
01010101011111
pickle.load() 00000111110011
10111100001111
De-Serialization 11111100010101
Un-Pickling

String,List,Tuple,Dictionary etc
Binary Files

Serialization is the process of transforming data or an object in memory


(RAM) to a stream of bytes called byte streams. These byte streams in a
binary file can then be stored in a disk or in a database or sent through a
network. Serialization process is also called pickling.

De-serialization or unpickling is the inverse of pickling process where a


byte stream is converted back to Python object.

The pickle module deals with binary files. Here,


data are not written but dumped and similarly,
data are not read but loaded.
Binary Files

The Pickle Module must be imported to load and dump


data.
The pickle module provides two methods - dump() and
load() to work with binary files for pickling and
unpickling, respectively.
Binary Files
Opening /Closing a Binary File

file=open(“class12.dat”, ‘rb’)

file=open(“class12.dat”, ‘wb’)

file.close()
Binary Files
Writing onto a Binary File-Pickling dump( ) Method

pickle.dump(<python-object>,<file-handle>)

List=[10,20, ‘Ram’, 40.5]


pickle.dump(list,file1)
Binary Files
Reading from a Binary File-un-Pickling load( ) Method

pickle.load(file-handle)
Binary Files

How to insert record in a


binary file?
How to read records from
a binary file?
Binary Files
Binary Files

Using Nested List


import pickle

# Write data to file


f = open("class11.dat", 'wb')
L=[]
while True:
rno = int(input("Enter roll number: "))
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
st = [rno, name, marks]
L.append(st)
ans = input("Want to enter more records? (y/n): ")
if ans == 'n':
break
pickle.dump(L, f)
f.close()

# Read data from file


f = open("class11.dat", 'rb')
d = pickle.load(f)
print(d)
f.close()
CSV Files

What is a CSV?

❖CSV files are the text files.


❖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 separator character of csv files is called a delimiter.Default
delimiter is comma(,).Other popular delimiters include the
tab(\t),colon(:),pipe(|) and semi colon(;) characters.
CSV Files

An example of CSV file is given below:


CODE,NAME,BASIC,YEARS
1001,KARAN GOEL,172000,14
1002,DISHA JAIN,177000,19
1003,CHANDAN KUMAR,179000,15
1004,TAHIRA KHAN,178000,16
1005,SUNIL SHARMA,175000,18
CSV Files
CSV Module
❖For working CSV files in Python, there is an inbuilt module called csv.
❖The Python csv module provides functions to write into CSV file and read
from CSV file.

To import csv module in our program use the following statement:

import csv

CSV Module provides two types of objects:

Reader:- to read from the csv files


Writer:- to write into the csv files
CSV Files
Opening / Closing CSV Files

Open the csv file:


file=open(“stu.csv”, ‘w’)

OR
file=open(“stu.csv”, ‘r’)

Close the csv file:


file.close()
CSV Files
Why csv files are so popular?
csv

csv

csv
Easy to Preferred Capable of
create export & storing large
import amounts of
format for data
databases
and
spreadsheets
CSV Files
Role of Argument newline in Opening of csv Files

While opening csv files ,in the open( ),you can specify an
additional argument newline, which is an optional but
important argument.
The role of newline argument is to specify how would
python handle newline characters while working with csv
files.
CSV Files
EOL characters used in different operating systems
Symbol/Char Meaning Operating System
CR [\r] Carriage Return Macintosh
LF [\n] Line Feed UNIX
CR/LF [\r \n] Carriage Return\Line MS-DOS , Windows
Feed
NULL [\0] Null Character Other OSs

Note: Additional optional argument as newline= ‘‘ (null


string;no space in between) with file open( ) will ensure that
no translation of end of line(EOL) character takes place.
CSV Files
Writing in CSV Files

csv.writer Returns a writer object which writes data into CSV File
<writerobject>.writerow() Writes one row of data onto the writer object

<writerobject>.writerows() Writes multiple rows of data onto the writer object


CSV Files
Reading in CSV Files

csv.reader() Returns a reader object which loads data from


csv file into an iterable after parsing delimited
data
How to insert record in a
CSV file?
How to read records from
a CSV file?
import csv
def write():
f=open("class12.csv",'w',newline="")
w=csv.writer(f,delimiter="|")
w.writerow(["Name","RollNo","Marks"])
w.writerows([["Raj", 1,85],["Aman",2,70]])
f.close()
def read():
f=open("class12.csv",'r')
d=csv.reader(f)
for r in d:
print(r)
f.close()
def search():
f=open("class12.csv",'r')
d=csv.reader(f,delimiter="|")
next(d)
for r in d:
if int(r[2])>80:
print(r)
write()
read()
search()
Using Nested List
import csv def read():
def write(): f=open("class12.csv",'r')
f=open("class12.csv",'w',newline="") d=csv.reader(f)
w=csv.writer(f) for r in d:
w.writerow(["Name","RollNo","Marks"]) print(r)
L=[]
while True: f.close()
name=input("Name:") def search():
rno=int(input("RollNo:")) f=open("class12.csv",'r')
marks=int(input("Marks:")) d=csv.reader(f)
data=[name,rno,marks] next(d)
L.append(data) for r in d:
ch=input("Want to Enter more Data(Y/N)?") if r[0]=="a":
if ch in 'Nn': print(r)
break write()
w.writerows(L) read()
f.close() search()

You might also like