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

Python

Uploaded by

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

Python

Uploaded by

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

MOTHR TERESA SENIOR SECONDARY COED SCHOOL

SUBJECT – COMPUTER SCIENCE


NOTES CLASS XII CHAPTER – Data File Handling

Data File Handling


Most of the program are transient they run for a short time and produce output , but when they end their data disappears
.This happens because the data entered is execute inside in main memory which is volatile in nature.
A files are persistent document or the data store on permanent storage device for long time which can be read , written or
rewritten according to the requirement. In other word, data is package up in the storage device as the data structure
called File.File stored on the secondary memory and transfer the data from secondary memory to main memory or vice
versa.
WHY USE FILES:
Data stored using file permanently stored on secondary storage media.
A file is a stream or sequence of character/data occupying named place on the disk like variable or function where a
sequence or related data is stored.
DATA FILE OPERATIONS:
Before we start working with the file, first we open the file after performing desirable operation ,it need to be closed so
the resource(memory) that are tied with the file are free.
Thus, the Python file handling takes place in the following order:
1) Opening a file
2) Performing operation(read , write) or process data
3) Closing the file
File Types
Before we discussed file operation , we should be aware of file types. Python allow us to create and manage two types of
file.
#TEXT FILE
# BINARY FILE
Text File-Text files are stored data in human readable form.A text file consists sequence of lines . A line is a sequence of
characters stores in term of ASCII code or UNICODES on permanent storage media. In text file each line in ended by a
special character End of Line(EOL). By default this EOL is the new line character ‘\n’.
So we use text file to store character data. For example test.txt
Binary File:
A binary file contains arbitrary binary data , usually numbers stored in the file which can be used for numerical operation
.So no character transitions can be carried out in binary file.As a result binary file are easier and faster than text files for
carried out reading and writing operation on data.

BASIC OPERATIONS WE CAN PERFORM ON FILE SUCH AS:


Creating file
Inserting data in file
Traversing a file or display data on screen
Appending data in file
Deleting data in file
Creating copy of a file
Updating data in file
OPENING A FILE:
To handle data file in Python has a built-in function open() to open a file. This function returns a file object, also called a
handle, as it is used to read write or modify the file accordingly. We can specify the mode while opening a file.
open( ) function takes the name of the file as the first argument.The second argument indication the mode of accessing
the file.
The syntax of open() function:
<File variable\object\handler>=open(“file_name”,access_mode)
First argument with open() function is the name of the file and the second argument describe the mode of a file means
how file will be used throughout the program. The default file mode is reading mode means when you open a file by using
open( ) function without second argument file is open in reading mode.
MODES FOR OPENING A FILE
>read mode(r) : to read the file
>write mode(w): to write in the new file
>append mode(a) : to write in already existing file at the end
For example :
If you want to open a file with name test.txt in read mode
Syntax:- f=open(“test.txt”)
In given example file is open default reading mode and f is the file variable or the file handler which used to access the
file in whole program

FILE MODES:
Mode Description
r Opens a file for reading only. The file pointer is placed at the beginning of the
file.This is the default mode.

rbOpens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode

r+Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

rb+Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.

wOpens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.

wbOpens a file for writing only in binary format. Overwrites the file if the file the file
exists. If does not exist, creates a new file for writing.

w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.

wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing .

a Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.

abOpens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.

a+Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.

ab+ Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.

file=open(“test.text”,”r+”)
Here is this statement we will open a file “test.txt” in reading and writing purpose. In above example .txt extension used
for identify the file as text file. It is not mandatory to specify file extension by default file when you open a file it open in
text type .But if you want to open a binary file extension we use for binary file is .dat is compulsory.
Another function to create or open a file is file().Its syntax and its usage is same as open() function.
close() function :
The close() function to close the file and free up system resources taken up by the open file. After calling f. close(),
attempts to use the file object will automatically fail. Python automatically close a file when the reference object of file is
reassigned to other file.It is good practice to use close() method to close a file.
Syntax:
Fileobject.close()

close() function breaks the link of file object and the file on disk.After closing file no task can be perform on file through
the file object.
f=open(“test.txt”)
print(“The name of the file is :”,f.name)
f.close()
Output
The name of the file is : test.txt

VARIOUS PROPETY OF FILE OBJECT:


Once file is open successful and file object can create, we can retrieve various detail related to file by using it associate
properties.
name :returns the name of open file.
mode: returns the mode of open file.
close: returns Boolean value, which indicate whether file is open or closed
readable: returns Boolean value,which indicate whether file is readable or not

f=open(“test.txt”) output:
print(“File Name :”,f.name) File Name : test.txt
print(“File mode :”,f.mode) File mode : r
print(“Is File readable :”,f. readable) Is File readable : True
print(“Is File closed :”,f.close) Is File closed : False
f.close() Is File closed : True
print(“Is File closed :”,f.close)

Writing To File:
We can write character data into file by using the following two method:
1)write(str):write() method take a string as a parameter and write it in the file.While writing data into file add EOL
character at the end of line as ‘\n’ otherwise all the data shall be written in single line without changing line or one line
space. Text file are store character data only so if you want to write integer data into file convert it into string.
Syntax:fileobject.write(string)
#A program to write name, rollno and marks of student in file.
f=open("stu.txt","w")
f.write("ram\n")
rollno=int(input("enter a rollno"))
f.write(str(rollno))
marks=int(input("enter a marks"))
f.write(str(marks))
f.close()
After execute the code file is created and stored in memory you can open stu.txt through file menu open option and
check data stored in file or not.

Note:
In above example data present in the file shall be overwritten every time when we run this program.
2) writelines(sequence): For writing a string at a time we use write method it can not be use for writing list,tuple etc. into
file. Sequence data type including string can be written using writeline() method in file.
Syntax:
Fileobject.writelines(sequence)
#A program to write subject namein file.
f=open("sub.txt","w")
l=["computer science\n","physics\n","economics\n","biology\n"]
f.writelines(l)
f.close()
Note:
You must have to be noticed we have used closed() method with every program.If you don’t want to use close() there is
an alternative method can be used in program.
With statement:
Using with statement ensure that all the resources allocate with file are deallocated automatically once we stop using
file.In with statement its not required to close the file.
Syntax: with open() as fileobject:
#A program to illustrate with statement.
with open("test.txt","w") as f:
f.write("python \n")
f.write("is an easy \n")
f.write("language \n")
print("Is file closed",f.close())
0utput:
Is file closed None
After execute the program when you open text file. Content stored in text file “test.txt”:
python
is an easy
language

APPENDINE TO FILE:
Append means to add if you want to add more data to a file which already existing and has some data in it.In such case we
open a file in ‘a’mode.In this mode data is add into already existing file at the end of the file after previous data.
In python we use ‘a’ mode to open a file in append mode. This means that:
 If the file is already exists data will add at the end of the file’s current content. If file does not exists , it will be
created and data will add.
Syntax: fileobject=open(“filename”,’a’)
#A program to add data in already existing file.
with open("test.txt","a") as f:
f.write("simple syntax of language\n")
f.write("make it an easy \n")
f.write("language \n")
Content stored in text file “test.txt” after append:
python
is an easy
language
simple syntax of language
make it an easy
language
READING FROM A FILE:
Python provide various method to read data from a file.We can read character data from file by using following read
method:
1)read( )-to read the entire data of the file in term of character string from top to end of file.
2)read(n) – This method reads n number of characters from the file, or if thenumber of character less then n it will
reads the entire file until end of file.
3) readline() – This method reads only one line as a string from the text file;starts reading from the top and including
the end of line charcter.
4) readlines() – This method reads entire line from the text file into a liststarts reading from the top and including the
end of line charcter and return a list of lines.
# A program to perform read and write operation in text file
f=open("test.txt","w")
f.write("I love car\n")
f.close()
f=open("test.txt","r")
r=f.read()
print("content stored in file",r)
f.close()

output: I love car

# A program to write multiple line and read data through readline() in text file
f=open("test.txt","w")
n=int(input("enter no of line you want to write in text file"))
for a in range(n):
str=input("enter string")
f.write(str)
f.write("\n")
f.close()
f=open("test.txt","r")
r=f.readline()
print("first line in file",r)
r1=f.readline()
print("second line in file",r1)
f.close()

Output:
enter no of line you want to write in text file3
enterstringhello user
enterstringu r working with
enterstringpython text file
first line in file hello user
second line in file u r working with

# A program to read all lines in list from text file 'test.txt'


f=open("test.txt","r")
lines=f.readlines()
for a in lines:
print(a,end=' ')
f.close()
Output:
hello user
u r working with
python text file
In above example “test.txt” is already stored file we just open it into read mode and read data.You can also read a
multiline text file by using for with open method.
Syntax: for a in open(“filenme”):
In above statement by default file is open in read mode and read data in line.
for a in open("test.txt")
print(a,end=' ')

#Write a program to read lines from text file diary.txt. count and display those line which start from alphabet ‘P’
f=open("diary.txt","w")
n=int(input("enter no of line you want to write in text file"))
for a in range(n):
str=input("enter string")
f.write(str)
f.write("\n")
f.close()
count=0
for a in open("diary.txt","r"):
if a[0]=='P':
print("line starts from alphabet P is",a)
count=count+1
print("total number of line starts from p",count)
Output:
enter no of line you want to write in text file3
enterstringhello user
enterstringPython is an easy language
enterstringsimple syntax
line starts from alphabet P is Python is an easy language
total number of line starts from p 1

#write a program to read a text file and count word ‘is’ come how many time in file
f=open("diary.txt","r")
r=f.read()
x=r.split()
count=0
for a in x:
if a=='is':
count=count+1
print("is comes in file",count,”times”)
f.close()
Output:
is comes in file 1 times
#write a program to read a text file and count alphabet ‘s’ come how many time in file
f=open("diary.txt","r")
r=f.read()
count=0
for a in r:
if a=='s':
count=count+1
print("s comes in file",count,"times")
f.close()
Output:
s comes in file 5 times

Copy the content from one text file to other file:


When you copy the content from one text file to other file you need to open two file first file which is already existing file
open in read mode and second or new file open in writing mode.
For example:
Write a program to copy line started from ‘u’ into another file.
f1=open("para.txt","w")
for a in open('test.txt'):
print(a)
if a[0]=='u':
f1.write(a)
f1.close()
f1=open("para.txt","r")
b=f1.read()
print(b)
f1.close()
Output:
hello user
u r working with
python text file
u r working with

Binary File operation:


We can write integer data structure into binary file such as a list or dictionary. we need to use the python module pickle
.Pickling refers to process of converting the structure to a byte stream before writing to a file. While reading
The content of the file a reverse process called Unpicking is used to convert the byte stream back to original structure.
So for storing data in binary format we use pickle module. First we import pickle Module. It provide two main method---
dump() and load(). For creation of binary file use pickle.dump() to write the object in file, which opened in binary access
mode.
Syntax:
Pickle.dump(object,fileobject)

#A program to write struture , list in binary file.


import pickle
f=open(“list.dat","wb")
L=[10,20,30,40,50]
Pickle.dump(L,f)
f.close()

#A program to write dictionary in binary file.


import pickle
f=open(“file.dat","wb")
dict1={“python”:90,”java”:80,”c++”:70}
Pickle.dump(dict1,f)
f.close()

Once data is stored using dump ,it can be used for reading. For reading data from a file, we have to use pickle.load() to
read the object from pickle file.

Syntax:
Object=Pickle.load(fileobject)

#A program to read dictionary from the binary file.


import pickle
f=open(“file.dat",“rb")
D=Pickle.load(f)
drint(“dictionary store in binary file=”,D)
f.close()
0utput:
dictionary store in binary file={“python”:90,”java”:80,”c++”:70}

#Program to write multiple object in binary file emp.dat


import pickle
f=open("emp.dat","wb")
n=int(input("enter number of line"))
for a in range(n):
ename=input("enter name of employee")
eid=int(input("enter employee ID"))
esalary=float(input("enter employee salary"))
L=[ename,eid,esalary]
pickle.dump(L,f)
f.close()
Output:
enter number of line2
enter name of employeeAjay
enter employee ID101
enter employee salary20000
enter name of employeeAman
enter employee ID102
enter employee salary22000

Program to display multiple object in binary file emp.dat


import pickle
f=open("emp.dat","rb")
for a in range(2):
r=pickle.load(f)
print(r)
f.close()
Output:
['Ajay', 101, 20000.0]
['Aman', 102, 22000.0]

Program to read binary file emp.dat and display the details of those employee whose salary is more then 20000 binary
file emp.dat
import pickle
f=open("emp.dat","rb")
for a in range(2):
r=pickle.load(f)
if r[2]>20000:
print(r)
f.close()
Output:
['Aman', 102, 22000.0]

Write a program to copy longest line into another file.


f1=open("para.txt","w")
long=" "
for a in open('test.txt'):
print(a)
if len(a)>len(long):
long=a
else:
f1.write(long)
f1.close()
f1=open("para.txt","r")
b=f1.read()
print(b)
f1.close()
Output:
hello user
u r working with
python text file
u r working with

Write a program to copy lines starts from lowercase character into another file.
f1=open("para.txt","w")
long=" "
for a in open('test.txt'):
print(a)
if a[0].islower():
f1.write(a)
f1.close()
f1=open("para.txt","r")
b=f1.read()
print(b)
f1.close()
Output :
hello user
u r working with
python text file
hello user
u r working with
python text file

WAP to replace the word first character start from alphabet ‘k’ to ‘c’ in a file data.txt.
f1=open("data.txt","w")
n=int(input("enter number of line "))
for a in range(n):
str=input("enter line")
f1.write(str)
f1.write('\n')
f1.close()
f1=open("data.txt","r")
b=f1.read()
print("data store in original file",b)
s=' '
for i in b:
if i=='k':
s=s+'c‘ output: enter number of line 2
else: enter line I love kar
s=s+ienter line kar in red kolour
f1.close() data store in original file
f1=open("data.txt","w") I love kar
f1.write(s)kar in red kolour
f1.close() data store in file after change
f1=open("data.txt","r") I love car
b=f1.read() car in red colour
print("data store in file after change",b)
f1.close()

Write a program to find ,count and display four character word in text file.
f1=open("test.txt","r")
b=f1.read()
print("data store in original file",b)
x=b.split()
count=0
for i in x:
iflen(i)==4:
print(i)
count=count+1
print("total four character word in file",count)
f1.close()
Output:
data store in original file
hello user
u r working with
python text file
user
with
text
file
total four character word in file 4

You might also like