Cbse Class 12 Computer Science File Handling4
Cbse Class 12 Computer Science File Handling4
Chapter 4
File Handling
Mostly .txt,.rtf are used as extensions to text files. Can have any application defined extension.
1 r - reading only.Sets file pointer at beginning of the file . This is the default mode.
2 rb – same as r mode but with binary file
3 r+ - both reading and writing. The file pointer placed at the beginning of the file.
4 rb+ - same as r+ mode but with binary file
5 w - writing only. Overwrites the file if the file exists. If not, creates a new file for writing.
6 wb – same as w mode but with binary file.
7 w+ - both writing and reading. Overwrites . If no file exist, creates a new file for R & W.
8 wb+ - same as w+ mode but with binary file.
9 a -for appending. Move file pointer at end of the file.Creates new file for writing,if not exist.
10 ab – same as a but with binary file.
11 a+ - for both appending and reading. Move file pointer at end. If the file does not exist, it creates a new
file for reading and writing.
12 ab+ - same as a+ mode but with binary mode.
close(): Used to close an open file. After using this method,an opened
file will be closed and a closed file cannot be read or written any more.
E.g. program
f = open("a.txt", 'a+')
print(f.closed)
print("Name of the file is",f.name)
f.close() #2 close text file
print(f.closed)
OUTPUT
False
Name of the file is a.txt
True
Visit : python.mykvs.in for regular updates
File Handling
3. Read/write text file
The write() Method
It writes the contents to the file in the form of string. It
does not return value. Due to buffering, the string may not
actually show up in the file until the flush() or close()
method is called.
The read() Method
It reads the entire file and returns it contents in the form of
a string. Reads at most size bytes or less if end of file
occurs.if size not mentioned then read the entire file
contents.
Visit : python.mykvs.in for regular updates
File Handling
Read/Write a Text file
write() ,read() Method based program
f = open("a.txt", 'w')
line1 = 'Welcome to python.mykvs.in'
f.write(line1)
line2="\nRegularly visit python.mykvs.in"
f.write(line2)
f.close()
f = open("a.txt", 'r')
text = f.read()
print(text)
f.close()
OUTPUT
Welcome to python.mykvs.in
Regularly visit python.mykvs.in
Note : for text file operation file extension should be .txt and opening mode
without ‘b’ & text file handling relevant methods should be used for file
operations.
Visit : python.mykvs.in for regular updates
File Handling
Writelines()
Using writelines() multiple lines can be written in file.
f = open(“d.txt", "a")
f.writelines(["See you soon!", "Over and out."])
f.close()
f = open("a.txt", 'r')
text = f.readline()
print(text)
text = f.readline()
print(text)
f.close()
OUTPUT
Welcome to python.mykvs.in
Regularly visit python.mykvs.in
Visit : python.mykvs.in for regular updates
File Handling
Read Text file
readlines([size]) method: Read no of lines from file if size is mentioned or all
contents if size is not mentioned.
e.g.program
f = open("a.txt", 'w')
line1 = 'Welcome to python.mykvs.in'
f.write(line1)
line2="\nRegularly visit python.mykvs.in"
f.write(line2)
f.close()
f = open("a.txt", 'r')
text = f.readlines(1)
print(text)
f.close()
OUTPUT
['Welcome to python.mykvs.in\n']
NOTE – READ ONLY ONE LINE IN ABOVE PROGRAM.
Visit : python.mykvs.in for regular updates
File Handling
Read a Text File
Iterating over lines in a file
e.g.program
f = open("a.txt", 'w')
line1 = 'Welcome to python.mykvs.in'
f.write(line1)
line2="\nRegularly visit python.mykvs.in"
f.write(line2)
f.close()
f = open("a.txt", 'r')
for text in f.readlines():
print(text)
f.close()
f = open("a.txt", 'r')
for text in f.readlines():
for word in text.split( ):
print(word)
f.close()
OUTPUT
Welcome
to
python.mykvs.in
Regularly
visit
python.mykvs.in
Visit : python.mykvs.in for regular updates
File Handling
Getting & Resetting the Files Position
The tell() method of python tells us the current position within the file,where as The seek(offset[,
from]) method changes the current file position. If from is 0, the beginning of the file to seek. If it is set
to 1, the current position is used . If it is set to 2 then the end of the file would be taken as seek
position. The offset argument indicates the number of bytes to be moved.
e.g.program
f = open("a.txt", 'w')
line = 'Welcome to python.mykvs.in\nRegularly visit python.mykvs.in' OUTPUT
f.write(line) 0
f.close()
b'Welcome'
f = open("a.txt", 'rb+') 7
print(f.tell()) b' to
print(f.read(7)) # read seven characters python.mykvs.in\r\nRe
print(f.tell())
print(f.read()) gularly visit
print(f.tell()) python.mykvs.in'
f.seek(9,0) # moves to 9 position from begining 59
print(f.read(5))
f.seek(4, 1) # moves to 4 position from current location
b'o pyt'
print(f.read(5)) b'mykvs'
f.seek(-5, 2) # Go to the 5th byte before the end b'vs.in'
print(f.read(5))
f.close()
Visit : python.mykvs.in for regular updates
File Handling
4. Modify a Text file
There is no way to insert into the middle of a file without re-writing
it. We can append to a file or overwrite part of it using seek but if we
want to add text at the beginning or the middle, we'll have to rewrite
it.
It is an operating system task, not a Python task. It is the same in all
languages.
What we usually do for modification is read from the file, make the
modifications and write it out to a new file called temp.txt or
something like that. This is better than reading the whole file into
memory because the file may be too large for that. Once the
temporary file is completed, rename it the same as the original file.
This is a good, safe way to do it because if the file write crashes or
aborts for any reason in between, we still have our untouched
original file.
Visit : python.mykvs.in for regular updates
File Handling
Modify a Text file
Replace string in the same File
fin = open("dummy.txt", "rt")
data = fin.read()
data = data.replace(‘my', ‘your')
fin.close()
f.write("\nthanks")
f.close()
f = open("a.txt", 'r')
text = f.read()
print(text)
f.close()
OUTPUT
Welcome to python.mykvs.in
Regularly visit python.mykvs.in
thanks
Visit : python.mykvs.in for regular updates
File Handling
Standard input, output,
and error streams in python
Most programs make output to "standard out“,input from "standard
in“, and error messages go to standard error).standard output is to
monitor and standard input is from keyboard.
e.g.program
import sys
a = sys.stdin.readline()
sys.stdout.write(a)
a = sys.stdin.read(5)#entered 10 characters.a contains 5 characters.
#The remaining characters are waiting to be read.
sys.stdout.write(a)
b = sys.stdin.read(5)
sys.stdout.write(b)
sys.stderr.write("\ncustom error message")
Visit : python.mykvs.in for regular updates
File Handling
Write and read a Binary file
#e.g. program
binary_file=open("D:\\binary_file.dat",mode="wb+")
text="Hello 123"
encoded=text.encode("utf-8")
binary_file.write(encoded)
binary_file.seek(0)
binary_data=binary_file.read()
print("binary:",binary_data)
text=binary_data.decode("utf-8")
print("Decoded data:",text)
Note :- Opening and closing of binary file is same as text file opening and closing.While
opening any binary file we have to specify ‘b’ in file opening mode.
In above program binary_file.dat is opened in wb+ mode so that after writing ,reading
operation can be done on binary file.String variable text hold text to be encoded before
writing with the help of encode method().utf-8 is encoding scheme.after writing text ,we
again set reading pointer at beginning with the help of seek() method.then read the text
from file and decode it with the help of decode() method then display the text.
f = open('d:/student.dat','rb')
while True:
try: Here we will iterate
rec = pickle.load(f)
print('Roll Num:',rec['Rollno'])
using infinite while
print('Name:',rec['Name']) loop and exit on end of
print('Marks:',rec['Marks']) file is reached.at each
except EOFError: iteration a dictionary
break data is read into rec
f.close()
and then values are
being displayed