Function and Text File
Function and Text File
Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default parameters,
positional parameters, function returning value(s), flow of execution, scope of a variable
(global scope, local scope)
Let us revise
A function is a block of code that performs a specific task.
Advantages of function: Reusability of code, Reduce size of code, minimum number
of statements, minimum storage, Easy to manage and maintain
Types of functions: Built-in-functions, Functions defined in module, User defined
function
Built-in functions are the functions whose functionality is pre-defined in python like
abs(), eval(), input(), print(), pow()
Some functions are defined inside the module like load() and dump() function defined
inside the pickle module.
A function that can be defined by the user is known as user defined function.
def keyword is used to define a function.
There is a colon at the end of def line, meaning it requires block
User Defined function involved two steps:
defining
calling
Syntax for user defined function:
def <function name>( [parameter list ]):
[””function’s doc string ””]
<statement>
[<statement>]
Python supports three types of formal arguments/ parameters: Positional Arguments,
Default parameters, Keyword (or named ) Arguments
Positional Arguments: When the function call statement must match the number and
order of arguments as defined in the function definition, this is called the positional
argument matching.
A parameter having default value in the function header is known as a default
parameter.
Keyword Arguments are the named arguments with assigned values being passed in
the function call statement.
A function may or may not return one or more values.
A function that does not return a value is known as void function and returns legal
empty value None.
Functions returning value are also known as fruitful functions.
The flow of execution refers to the order in which statements are executed during a
program.
A variable declared in a function body (block) is said to have local scope. i.e. it can
be accessed within this function.
A variable declared outside of all functions/top level of segment of a program is said
to have global scope. i.e. it can be accessible in whole program and all blocks (
functions and the other blocks contained within program.
21
Page
MIND MAP ON FUNCTION
Function: A function is a group of statements that exists within a
program for the purpose of performing a specific task.
Types of Arguments/Parameters
1. (a) None
2. (c) Both function name and parameter list
3. (c) def
4. (d) return number
5. (c) def f(a=1, b=1, c=2):
6. (a) You can pass positional arguments in any order.
7. (b) A global variable
8. (b) LEGB
9. (c) A is True but R is False
10. (b) Flow of execution
11. (c) Both Statements are Correct
12. c) scope
On the basis of the above code, choose the right statement which will be executed when
different inputs for pay and location are given
(i) Input: location = “Chennai”, pay = 50000
a. Statement 1 b. Statement 2 c. Statement 3 d. Statement 4
(ii) Input: location = “Surat” ,pay = 50000
a. Statement 2 b. Statement 4 c. Statement 5 d. Statement 6
(iii) Input- location = “Any Other City”, pay = 1
a Statement 1 b. Statement 2 c. Statement 4 d. Statement 6
28
Page
(iv) Input location = “Delhi”, pay = 500000
a. Statement 6 b. Statement 5 c. Statement 4 d. Statement 3
Q2. Kids Elementary is a Playway school that focuses on “Play and learn” strategy that helps
toddlers understand concepts in a fun way. Being a senior programmer, you have taken
responsibility to develop a program using user-defined functions to help children differentiate
between upper case and lower case letters/ English alphabet in a given sequence. Make sure
that you perform a careful analysis of the type of alphabets and sentences that can be included
as per age and curriculum. Write a python program that accepts a string and calculates the
number of upper case letters and lower case letters.
Answer:
def string_test(s):
d={"UPPER_CASE":0,"LOWER_CASE":0}
for c in s:
if [Link]():
d["UPPER_CASE"]+=1
elif [Link]():
d["LOWER_CASE"]+=1
else:
pass
print("Original String:",s)
print("No. of Upper Case Characters:",d["UPPER_CASE"])
print("No. of Lower Case Characters:",d["LOWER_CASE"])
string_test("Play Learn and Grow")
Q2. Observe the following code and select appropriate answers for the given questions:
total=1
def multiply(l): # line1
for x in l:
total # line2
total*=x
return # line3
l=[2,3,4]
print(multiply( ), end=” “) # line4
print(“ , Thank You”)
(i) Identify the part of function in # line1
(a) Function header (b) Function calling (c) Return statement (d)Default argument
(ii) Which of the keyword is used to fill in the blank for # line2 to run the program
without error.
(a) eval (b) def (c) global (d) return
(iii) Which variable is going to be returned in # line3
(a) total (b) x (c) l (d) None
(iv) Which variable is required in the # line4
(a) total (b) x (c) l (d) None
(v) In the # line4 the multiple(l) is called
(a) Caller (b) Called (c) Parameters (d) Arguments
Answer: (i) (a) Function header
(ii) (c) global
(iii) (a) total
(iv) (c) l
(v) (a) Caller
30
Page
FILE HANDLING – TEXT FILES
I. INTRODUCTION:
• 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).
• Since Random Access Memory (RAM) is volatile (which loses its data when
the computer is turned off), we use files for future use of the data by
permanently storing them.
• 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.
• Hence, in Python, a file operation takes place in the following order:
– Open a file
– Read or write (perform operation)
– Close the file
II Types of File in Python
There are two types of files in Python and each of them are explained below in detail
with examples for your easy understanding. They are:
1) Binary file 2) Text file
II. Text files in Python
• A text file is usually considered as sequence of lines. Line is a sequence of
characters (ASCII), stored on permanent storage media. Although default
character coding in python is ASCII but supports Unicode as well.
• In text file, each line is terminated by a special character, known as End of Line
(EOL). From strings we know that \n is newline character.
• At the lowest level, text file is collection of bytes. Text files are stored in human
readable form. They can also be created using any text editor.
• Text files don’t have any specific encoding and it can be opened in normal text
editor itself.
Example of Text Files:
• Web standards: html, XML, CSS, • Tabular data: csv, tsv etc.
JSON • Configuration: ini, cfg, reg etc
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
III. OPENING OR CREATING A NEW FILE IN PYTHON
• The method open() is used to open an existing file or creating a new file. If the
complete directory is not given then the file will be created in the directory in
which the python file is stored. The syntax for using open() method is given
below.
– Syntax:
– file_object = open( file_name, “Access Mode”, Buffering )
• The open method returns file object which can be stored in the name file object
(file-handle).
File name is a unique name in a directory. The open() function will create the file with
the specified name if it is not already exists otherwise it will open the already existing
file.
File Access Modes:
• The access mode: it is the string which tells in what mode the file should be
opened for operations. There are three different access modes are available in
python.
• Reading: Reading mode is crated only for reading the file. The pointer will be
at the beginning of the file.
• Writing: Writing mode is used for overwriting the information on existing file.
32
Page
• Append: Append mode is same as the writing mode. Instead of over writing
the information this mode append the information at the end.
• Below is the list of representation of various access modes in python.
Access modes in Text Files
• ‘r' – Read Mode: Read mode is used only to read data from the file.
• ‘w' – Write Mode: This mode is used when you want to write data into the file
or modify it. Remember write mode overwrites the data present in the file.
• ‘a' – Append Mode: Append mode is used to append data to the file. Remember
data will be appended at the end of the file pointer.
• ‘r+' – Read or Write Mode: This mode is used when we want to write or read
the data from the same file.
• ‘a+' – Append or Read Mode: This mode is used when we want to read data
from the file or append the data into the same file.
Buffering:
• Buffering is the process of storing a chunk of a file in a temporary memory
until the file loads completely. In python there are different values can be given.
If the buffering is set to 0 , then the buffering is off. The buffering will be set
to 1 when we need to buffer the file.
Examples of Opening TEXT Files in Python
# open file in current directory
• f = open("[Link]“, “r”)
# specifying full path
– f = open(r“D:\temp\[Link]“, “r”) #–raw string
• f = open(“D:\\temp\\[Link]“, “r”) #-absolute path
IV. CLOSING FILES IN PYTHON
• After processing the content in a file, the file must be saved and closed. To do this
we can use another method close() for closing the file. This is an important method
to be remembered while handling files in python.
• Syntax: file_object.close()
string = "This is a String in Python"
my_file = open(my_file_name.txt,"w+",1)
my_file.write(string)
my_file.close()
print(my_file.closed)
V. READING INFORMATION IN THE 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.
– read([n])
– readline([n])
– readlines() – all lines returned to a list
Here, n is the number of bytes to be read.
Example 1:
my_file = open(“C:/Documents/Python/[Link]”, “r”)
print(my_file.read(5))
Output:
Hello
Here we are opening the file [Link] in a read-only mode and are
reading only the first 5 characters of the file using the
my_file.read(5) method.
Example 2:
my_file = open(“C:/Documents/Python/[Link]”, “r”)
print(my_file.read())
33
Page
Output:
Hello World
Hello Python
Good Morning #Here we have not provided any argument inside
the read() function.
#Hence it will read all the content present inside
the file.
Example 3:
my_file = open(“C:/Documents/Python/[Link]”, “r”)
print(my_file.readline(2))
Output:
He
This function returns the first 2 characters of the next line.
Example 4:
my_file = open(“C:/Documents/Python/[Link]”, “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 5:
my_file = open(“C:/Documents/Python/[Link]”, “r”)
print(my_file.readlines())
Output:
[‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’]
Here we are reading all the lines present inside the text file including the newline
characters.
Example 5: Reading a specific line from
a File Output:
line_number = 4 How are You
fo =
open(“C:/Documents/Python/[Link]”,
’r’) #In this example, we are trying to read
currentline = 1 only the 4th line from the ‘[Link]’ file
for line in fo: using a “for loop”.
if(currentline == line_number):
print(line)
break
currentline = currentline +1
VI. WRITE TO A PYTHON TEXT FILE
• In order to write data into a file, we must open the file in write mode.
• We need to be very careful while writing data into the file as it overwrites the
content present inside the file that we are writing, and all the previous data will be
erased.
• We have two methods for writing data into a file as shown below.
write(string) and writelines(list)
Example 1:
my_file = open(“C:/Documents/Python/[Link]”, “w”)
my_file.write(“Hello World”)
34
Page
The above code writes the String ‘Hello World’ into the ‘[Link]’ file.
• The first line will be ‘Hello World’ and
my_file =
as we have mentioned \n character,
theo“w
pe”n)(“C:/Documents/Python/[Link]”,
cursor
file andwill
thenmove
write to the next
‘Hello line of the
Python’.
my_file.write(“Hello World\n”)
• Remember if we don’t mention \n
my_file.write(“Hello Python”)
character, then the data will be written
continuously in the text file like ‘Hello
WorldHelloPython’
Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“C:/Documents/Python/[Link]”, “w”)
my_file.writelines(fruits)
The above code writes a list of data into the ‘[Link]’ file simultaneously.
Append in a Python Text 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:
my_file = open(“C:/Documents/Python/[Link]”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the
end of the ‘[Link]’ file
Example 2:
my_file = open(“C:/Documents/Python/[Link]”, “a+”)
my_file.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end
of
the ‘[Link]’ file in a new line
flush() function
• When we write any data to file, python hold everything in buffer (temporary
memory) and pushes it onto actual file later. If you want to force Python to write
the content of buffer onto storage, you can use flush() function.
• Python automatically flushes the files when closing them i.e. it will be implicitly
called by the close(), BUT if you want to flush before closing any file you can use
flush()
REMOVING WHITESPACES AFTER READING FROM TEXT FILE
• read() and readline() reads data from file and return it in the form of string and
readlines() returns data in the form of list.
• All these read function also read leading and trailing whitespaces, new line
characters. If we want to remove these characters you can use functions
– strip() : removes the given character from both ends.
– lstrip(): removes given character from left end
– rstrip(): removes given character from right end
File Pointer
• Every file maintains a file pointer which tells the current position in the file
where reading and writing operation will take.
• When we perform any read/write operation two things happens:
– The operation at the current position of file pointer
– File pointer advances by the specified number of bytes.
35
Page
1- MARK QUESTIONS
1. To read three characters from a file object f, we use ……… .
(a) [Link](3) (b) [Link]() (c) [Link]() (d) [Link]()
2. The files that consists of human readable characters
(a) binary file (b) text file (c) Both (a) and (b) (d) None of these
3. Which function is used to write a list of string in a file?
(a) writeline() (b) writelines() (c) writestatement() (d) writefullline()
4. What will be the output of the following Python code?
myFile = None
for i in range (8):
with open(“[Link]”, “w”) as myFile:
if i > 5:
break
print([Link])
1. (a) ) 2. (b) 3. (a) 4. (a)5. (d) 6. (b) 7. (b) 8. (a)9. (b) 10.
2 MARK QUESTIONS
Q1. Write a single loop to display all the contens of a text file [Link] after removing leading
and trailing WHITESPACES
out=open('[Link]','w')
[Link]('hello,world!\n')
[Link]('how are you')
[Link]( )
open('[Link]').read( )
37
Page
Q3. Read the code given below and answer the questions
f1=open('[Link]','w')
[Link]('bye')
[Link]()
If the file contains 'GOOD' before execution, what will be the content of the file after
execution of the code
Q4. Observe the following code and answer the follow
f1=open("mydata","a")
#blank1
[Link]()
(i) what type of file is mydata
(ii) Fill in the blank1 with statement to write "abc" in the file "mydata"
Q5. A given text file [Link] contains :
Line1\n
\n
line3
Line 4
\n
line6
What would be the output of following code?
f1=open('[Link]')
L=[Link]()
print(L[0])
print(L[2])
print(L[5])
print(L[1])
print(L[4])
print(L[3])
Q6. In which of the following file modes the existing data of the file will not be lost?
i) rb
ii) w
iii) a+b
iv) wb+
v) r+
vi) ab
vii) w+b
viii)wb
ix) w+
Q7. What would be the data types of variables data in following statements?
i) Data=[Link]( )
ii) Data=[Link](10)
iii) Data=[Link]()
iv)Data=[Link]()
Q8 Suppose a file name [Link] store alphabets in it then what is the output of the following
code
f1=open("[Link]")
size=len([Link]())
print([Link](5))
Q9. What is standard input, output and error steams?
Q10. Write a short note on flush() function.
38
Page
ANSWER – 2-MARK QUESTIONS
Ans1 for line in open(“[Link]”):
print([Link]())
Ans2 The output will be
Hello,world!
How are you?
The first line of code is opening the file in write mode,the next two line writes text t file .the
last line
opens the file and from that reference reads the file [Link]() performs the same functions
as open().Thus,the file(“[Link]”)will give the references to open the file on which read() is
applied.
Ans3 The file would now contains “Bye”only because when an existing file is openend in
write mode .it
truncates the existing data in file .
Ans4 i) Text file
ii) [Link](“abc”)
Ans5 Line1
Line3
Line 6
Line 4
Ans6 ab and a+b mode
Ans7 a) string b)string c)string d)list
Ans 8 No Output
Explanation: the [Link]() of line 2 will read entire content of file and place the file pointer at
the
end of file. for [Link](5) it will return nothing as there are no bytes to be read from EOF and,
thus,print statement prints nothing.
Ans 9
Standard input device(stdin) reads from the keyboard
Standard output device(stdout)- prints to the display and can be redirected as standard
input
Standard error device(stderr)- Same as stdout but normally only for errors. Having error output
separately allows the user to divert regular output to a file and still be able to read error messages.
Ans 10
While writing, Python writes everything into a buffer and pushes it into file at a later
time.
When flush() function is called it immediately empties the buffer and writes into the
file.
This function is called automatically when file is closed.
39
Page
3 MARK QUESTIONS
Q1. Write a python code to find the size of the file in bytes, number of lines and number
of words.
# reading data from a file and find size, lines, words
f=open(‘[Link]’,’r’)
str=[Link]( )
size=len(str)
print(‘size of file n bytes’,size)
[Link](0)
L=[Link]( )
word=[Link]( )
print(‘Number of lines ’,len(L))
print(‘Number of words ’,len(word))
[Link]( )
Q2. Write code to print just the last line of a text file “[Link]”.
Ans: fin=open(“[Link]”,”r”)
lineList=[Link]()
print(“Last line = “, lineList[-1])
Q.3 Write a program to count the words “to” and “the” present in a text file
“[Link]”.
Ans.
fname = "[Link]"
num_words = 0
f= open(fname, 'r')
words = [Link]().split()
for a in words:
if ([Link]() == “to” or [Link]() == “the” ):
num_words = num_words + 1
print("Number of words:", num_words)
[Link]()
Q.4. Write a program to display all the lines in a file “[Link]” along with line/record
number.
Ans.
fh=open("[Link]","r")
count=0
lines=[Link]()
for a in lines:
count=count+1
print(count,a)
[Link]()
Q. 5 Write a program to display all the lines in a file “[Link]” which have the word
“to” in it.
Ans.
fh=open("[Link]","r")
count=0
lines=[Link]()
for a in lines:
if ([Link]().count(“to”) > 0) :
print(a)
[Link]()
40
Page
3- MARK QUESTIONS
1. Write a python program to create and read the [Link] file in one go and print
the contents on the output screen.
Answer:
# Creating file with open() function
f=open("[Link]","w")
[Link]("My city is very clean city.")
[Link]()
# Reading contents from [Link] file
f=open("[Link]","r")
dt = [Link]()
print(dt)
[Link]()
2. Consider following lines for the file [Link] and predict the output:
Friends are crazy, Friends are naughty !
Friends are honest, Friends are best !
Friends are like keygen, friends are like license key !
We are nothing without friends, Life is not possible without friends !
f = open("[Link]")
l = [Link]()
l2 = [Link](18)
ch3=[Link](10)
print(l2)
print(ch3)
print([Link]())
[Link]()
Output:
Friends are honest
, Friends
are best !
Explanation:
In line no. 2, [Link]() function reads first line and stores the output string in l but not printed
in the code, then it moves the pointer to next line in the file. In next statement we have
[Link](18) which reads next 18 characters and place the cursor at the next position i.e.
comma (,) , in next statement [Link](10) reads next 10 characters and stores in ch3 variable and
then cursor moves to the next position and at last [Link]() function print() the entire line.
3. Write a function count_lines() to count and display the total number of lines from the
file. Consider above file – [Link].
def count_lines():
f = open("[Link]")
cnt =0
for lines in f:
cnt+=1
lines = [Link]()
print("no. of lines:",cnt)
[Link]()
4. Write a function display_oddLines() to display odd number lines from the text file.
Consider above file – [Link].
def display_oddLines():
f = open("[Link]")
cnt =0
for lines in f:
41
Page
cnt+=1
lines = [Link]()
if cnt%2!=0:
print(lines)
[Link]()
5. Write a function cust_data() to ask user to enter their names and age to store data in
[Link] file.
def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("[Link]","w")
[Link](data)
[Link]()
4 MARK QUESTIONS
Q1. This question consists of 6 sub-questions . Attempt any 5 questions.
Below is a program to delete the line having word (passed as argument). Answer the
questions that follow to execute the program successfully.
def filedel(word) :
file1 = open(“[Link] ”,“ ”) # Statement 1
nfile = open(“[Link]”, “w”)
while True :
line = file1. # Statement 2
if not line :
break
else :
if word in line :
# Statement 3
else :
print(line)
nfile. (line) # Statement 4
[Link]()
. close() # Statement 5
filedel(‘write’)
(i). In which mode, program should open the file to delete the line in statement 2?
(a) w (b) r (c) r+ (d) a+
(ii). Choose the correct option to fill up the blank in line marked as Statement 3.
(a) read() (b) read(n) (c) readlines() (d) readline()
(iii). Identify the missing code for blank space in line marked as Statement 4.
(a) True (b) Flag (c) pass (d) False
(iv). Choose the correct option to fill up the blank in line marked as Statement 5.
(a) read (b) write (c) writelines (d) writeline
(v). Choose the correct option to fill up the blank in line marked as Statement 6.
(a) file 1 (b) file (c) nfile (d) None
Answer – 1
(i). (b) (ii). (d) (iii) (c) (iv). (b) (v). (c)
(i). Choose the correct option to fill up the blank marked as Line 1.
(a) status (b) “[Link]” (c) [Link] (d) [Link]
(ii). Choose the correct option to fill up the blank marked as Line 2.
(a) 0 (b) 1 (c) False (d) True
(iii). Which function will be used to read the content of file marked as Line 3?
(a) readline() (b) readlines() (c) read() (d) read(n)
(iv). Choose the correct option to fill up the blank marked as Line 4.
(a) continue (b) break (c) goto (d) label
(v) Which value will be assign to variable count in Line 5?
(a) count −1 (b) count*i (c) count +1 (d) count + i
(vi). Identify the missing code in Line 6.
(a) [Link] (b) [Link] (c) [Link]() (d) [Link]()
Answer – 2
(i). (b) (ii). (d) (iii). (a) (iv). (b) (v). (c) (vi). (d)
MIND MAP
Binary Files
FILE HANDLING
Text Files