0% found this document useful (0 votes)
12 views23 pages

62 BDD

Uploaded by

palashtiwari07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

62 BDD

Uploaded by

palashtiwari07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

In order to ensure the success

of online class
• Keep your microphone and video on mute so that
there are no disturbances
• Please use chat to ask queries/ answer questions
when prompted
• As far as possible try to use laptop/pc
• The students must leave the group once the session
is over. Please do not use this platform for personal
chat/groups
DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR
Learning Objectives
Introduction of rstrip(), lstrip() and strip() methods
Random access functions-seek() and tell()
File object attributes: closed, name, mode

Os module functions


os.getcwd()
os.path.abspath(filename)
os.path.isfile(filename)

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Revision of previous class
Readlines() function - Reads all the lines and return
them as each line a string element in a list.

Handling Delimited files

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Handling delimited files using readlines()

Example 1: To find the average marks from file Marks.txt


def findavgmarks():
Marks.txt
f=open("marks.txt","r")
a=f.readlines() Name:Marks
a=a[1:]
sm=0 Anuj:89
for i in a: Satvik:89
if(len(i)>2): Kiara:78
marks=i.split(":") Mrigya:45
sm=sm+float(marks[1]) Kritika:90
return(sm/len(a)) Pankaj:35
print(findavgmarks()) Priya:66
DEEPSHIKHA SETHI ---XII COMPUTER SCIENCE ----AIS MAYUR VIHAR
H.W. To do Practical List Question -1
1) Write a function to create a text file containing following data:
Neither apple nor pine are in pineapple. Boxing rings are square.
Writers write, but fingers don’t fing. Overlook and oversee are opposites.
A house can burn up as it burns down. An alarm goes off by going on.

a) Read back the entire file content using read( ) or readlines( ) and display on the screen.
b) Append more text of your choice in the file and display the content of file with line numbers prefixed to
line.
c) Display last line of file.
d) Display first line from 10th character onwards.
e) Read and display a line from the file. Ask user to provide the line number to be read.
f) Find the frequency of words beginning with every letter i.e.
(for the above example)
Words beginning with a: 5
Words beginning with n: 2
Words beginning with p: 2
Words beginning with o: 5 and so on

DEEPSHIKHA SETHI ---XII COMPUTER SCIENCE ----AIS MAYUR VIHAR


Removing white spaces after
reading from file
strip() – removes the given character from both end of lines(left end
and right end)
rstrip() – removes the given character from trailing end i.e right end
lstrip() – removes the given character from leading end i.e. left end

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Removing white spaces after
reading from file

Output
12
----------------
11
----------------
4

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Example:

A file contains information in following form:


Rollno~marks1~marks2~marks3
12~34.50~64.75~55.50\n

Line = fin.readline().rstrip(‘\n’)
Record=line.split(‘~’)

Output:
Record = [‘12’, ‘34.5’, ’64.75’, ‘55.50’]
DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR
Handling delimited files using readlines()
Task: To use the same file and find the student having highest
marks f=open("Marks.txt",'r')
a=f.readlines()
a=a[1:]
print(a)
high=0
for i in a:
i=i.rstrip('\n')
i=i.split(',')
print(i)
marks=int(i[2])
print(marks)
if (marks>high): #Type error: '>' not supported between instances of 'int' and 'str'
high=marks
name=i[1]
print(name,high)
f.close()

DEEPSHIKHA SETHI ---XII COMPUTER SCIENCE ----AIS MAYUR VIHAR


Random Access Functions
When you read or write in a file, then by default the
access is sequential. Every read and write operation
takes place at the current position of file pointer.

Python provides two functions that help you


manipulate the position of file-pointer and thus you
can read and write from desired position in the file.

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Random Access Functions-
Handling File Pointer

seek() – This function changes the position of file-


pointer by
placing the file-pointer at the specified
position.

tell() - Returns the cursor position

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Handling File Pointer
Offset Whence

Reference position
seek() No of bytes
to be moved from where the byte
has to be moved
Fileobject.seek(offset,whence)
0 means beginning
1 means current
2 means end
tell()
Fileobject.tell()

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Handling File Pointer
Aditya kind
f=open("newfile.txt","r") Aryan versatile
seek() and tell()print(f.tell()) Manasvi diligent
Mahi confident
Examples f.close() Devansh cheerful
f=open("newfile.txt","a") Mehul calm
Praneet carefree
print(f.tell())
f.close() Output:
f=open("newfile.txt","r")
0
f.seek(5,0)
105
print(f.readline()) a kind

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Handling File Pointer
Aditya kind
f=open("newfile.txt","r") Aryan versatile
seek() and tell()print(f.readline()) Manasvi diligent
Mahi confident
Examples print(f.tell()) Devansh cheerful
f.seek(20,0) Mehul calm
Praneet carefree
print(f.readline())
Output:
Aditya kind

12
rsatile

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Initially file-pointer's position in at: 0 Aditya kind
5 bytes read are: Adity Aryan versatile
After previous read, current position of file pointer: 5 Manasvi diligent
Next 10 bytes read: a kind Mahi confident
Ary Devansh cheerful
After previous read, current position of file pointer: 16 Mehul calm
Come at the begining Praneet carefree
Will place the file pointer at 30th byte from the beginning 3

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Let’s revise
Q: Write appropriate statements to do the following:
(i) To open a file named “Emp.dat” for output.
ob=open(“Emp.dat”,”w”)

(ii) To go to the beginning of the file at anytime.


ob.seek(0)

(iii) To go to the 20th byte in a file.


ob.seek(20)

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


Handling File Pointer
seek() important characteristics f=open("newfile.txt","r")
print(f.seek(15,0))
• whence is optional and default is 0

• seek() returns the byte position f=open("newfile.txt","r")


f.seek(19,0)
after moving the cursor
f.seek(10,1) #Error
f.seek(-5,2) #Error
• seek() supports >0 offset only
when whence is 0
DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR
File object attributes
• File.closed
Returns true if file is closed, false otherwise.

• File.mode
Returns access mode with which file was opened.

• File.name : Simple and efficient storage solution -


Files
Returns name of the file.

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


File object attributes
Find the output

f=open('fruits.txt','r') False
print(f.closed) fruits.txt
print(f.name) r
print(f.mode)

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


The flush( ) function
• Anything written using write() is held in input buffer
• Python pushes it to the actual file later
• flush() forces the contents to the actual file on the storage device
• close() method allows Python to automatically flush the contents

DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR


The flush( ) function
f=open('out.txt','w+')
f.write('The output is \n')
f.write("My" + "work-status"+"is")
With this statement, the strings written so far,
f.flush() i.e., "The output is" and "My work-status is“
have been pushed on to actual file on disk.
s='OK'
f.write(s)
f.write('Finally Over\n')
The flush function ensures that whatever is
f.flush() held in Output buffer, is written on to the actual
file on disk
f.close()
DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR
OS Module
Files are always stored in current folder / directory by default. The os (Operating
System) module of python provides various methods to work with file and folder /
directories. For using these functions, we have to import os module in our program.
Some of the useful methods, which can be used with files in os module are as
follows:
1. os.getcwd() to know the name of current working directory

2. os.path.abspath(filename) will give us the complete path name of the data file.

3. os.path.isfile(filename) will check, whether the file exists or not.

4. os.remove(<filename>) will delete the file. Here filename has to be the complete
path of file.

5. os.rename(“Old file name”,”New file name”) will change the name of filename1
with filename2.
DEEPSHIKHA SETHI ----XII COMPUTER SCIENCE ---- AIS MAYUR VIHAR

You might also like