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

Text File

Uploaded by

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

Text File

Uploaded by

Geetha S
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 96

FILE HANDLING - INTRODUCTION

File Handling is a mechanism by which we can read data of disk files in


python program or write back from python program to disk files.

So far in our python program the standard input coming from keyboard
and output is going to monitor i.e no where data is stored permanently and
entered data is present as long as program is running BUT file handling
allows us to store data entered through python program permanently in
disk file and later on we can read back the data.
FILE HANDLING

DATA FILES
⮚ It contains data pertaining to a specific
application, for later use. The data files can be
stored in two ways : -
1. Text File
2. Binary File
FILE HANDLING – TEXT FILE

Text File stores information in ASCII OR UNICODE character ( the


one which is default for your programming platform).

In text file each line of text is terminated with a special character


known as EOL ( End of Line ) character.

In python by default this EOL character is the newline character (‘\


n’) or carriage-return, newline combination (‘ \r \ n )
Extension : .txt
FILE HANDLING – BINARY FILE
❖Binary file stores the information in the form of a stream of bytes.
❖Hence binary files cannot be read by humans.
❖A binary file contains information in the same format in which the information is
held in memory, hence no translation is required. ( i.e high level language( c,c+
+,java,Python etc., to low level language –machine language )
❖In binary file, there is no delimiter( i.e new line character) for a line.
❖Binary files are faster and easier for a program to read and write than in text
files.
❖As long as binary files cannot be read by humans , they are the best way to store
program information.
❖Binary files are saved with the extension .dat they also take variety of
extensions.
❖Most of the files apart from text file that we see in our computer system are
binary files
FILE HANDLING – BINARY FILE

image files -- .jpg, .gif, .imp, .png etc


video files -- .mp4, .3gp, .mkv, .avi etc
audio files -- .mp3, .wav, .mka etc
archive files -- .zip, .rar, etc
FILE HANDLING – BINARY FILE
FILE HANDLING – BINARY FILE
FILE HANDLING – BINARY FILE

BINARY ACADEMY MRS. GEETHA ROBIN M.SC.,M.PHIL.,M.ED ( COMPUTER SCIENCE )


FILE HANDLING
The text file can be of two types :
1. Regular Text File : These are the text files which stores the text file in
the same form as typed. Here the newline character ends a line and the
text translation take place. These files have a file extension as .txt.

2. Delimited Text files : In these text files, a specific character is stored to


separate the values.
🡪 TSV : Tab Separated Files – Tab character is used to separate a value
🡪 CSV : Comma Separated Values – Comma is used to separate the values

BINARY ACADEMY MRS. GEETHA ROBIN M.SC.,M.PHIL.,M.ED ( COMPUTER SCIENCE )


FILE HANDLING - Operations

⮚Reading data from the files

⮚Writing data to files

⮚Appending data to files


Text file – Opening Files

open() function
Syntax :
<file_objectname> = open ( < filename >) (or)

<file_objectname> = open ( < filename >, <mode>)


Eg:

f = open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","w”)
(or)
f = open( “ student.txt”,”w”)
File Access Modes
Text file Binary file
mode mode Description
Notes
‘r’ ‘rb’ read only Default mode : File must exist already, otherwise Python raises
FileNotFoundError.
‘w’ ‘wb’ write only 🡪 If the file does not exist, file is created.
🡪 If the file exists, Python will truncate existing
data and over-write in the file. Hence this mode
must be used with caution.
‘a’ ‘ab’ Append 🡪 file is in write only mode.
🡪 If the file exists, the data in the file is retained and new data being
written will be appended to the end.
🡪 If the file does not exist, Python will create a new file.
‘r+’ ‘r+b’ or read and write 🡪 File must exist otherwise error is raised
‘rb+’ 🡪 Both reading and writing operations can take place.

‘w+’ ‘w+b’ write and read 🡪 File is created if does not exist.
or 🡪 If file exists, file is truncated ( past data is lost )
‘wb+’ 🡪 Both reading and writing operations can take place.

‘a+’ ‘a+b’ or write and read 🡪File is created if does not exist.
‘ab+’ 🡪 If file is exists, file’s existing data is retained ; new data is appended.
🡪 Both reading and writing operations can take place.
CLOSING FILES
< file handle> . close( )

The close( ) function breaks the link of file-object and the file on the disk.
After close( ), no tasks can be performed on that file through the file-
object.

Ex :
f = open(“student.txt”,”w”)
-----
-----
f.close()
Reading from text file
f=open(“student.txt”,’r’)

1. f.read( )
2. f. read(n)
3. f.readline( ) and
4. f.readlines ( )
READING FROM TEXT FILES

To read a file, the file should be existing already.


Hence user should create a file already and save it with file name.
Steps to create a file :
1. Right click on desktop
2. Select new 🡪 text document
3. Double click on new file and select file menu 🡪 SaveAs option and give
the file name and click save button
4. Now you can see the file created on desktop
Creating new TEXT FILE
You can see the student
file created on the
desktop
Creating new TEXT FILES

Double click on the student file


and type the content in the file,
save and close the file
TO TYPE THE FULL PATH

Right click
on the file and
select properties
The filename (student) Properties
Dialogue box will open
PATH

In General tab from Location


select the full path with
the mouse
and copy the path.
PATH

Now paste it in the coding and add slash

C:\Users\ADMIN\OneDrive\Desktop

“C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt",“r"

f = open(“C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt",“r“)
Reading from text file
f=open(“student.txt”,’r’)

1. f.read( )
2. f. read(n)
3. f.readline( ) and
4. f.readlines ( )
Reading from text file
student.txt
f=open(“student.txt”,’r’) GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
1. f.read() GOOD EVENING
GOOD DAY

reads the entire content of the file byte by byte i.e character by
character
🡪 type – string

GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
Reading from text file
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
a=f.read()
print(a) student.txt
GOOD MORNING
f.close() GOOD EVENING
GOOD AFTERNOON
Output : GOOD EVENING
GOOD DAY
GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
Reading from text file
f=open(“student.txt”,’r’)
read( )
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
a=f.read() GOOD MORNING
print(len(a)) GOOD EVENING
GOOD AFTERNOON
f.close() GOOD EVENING
GOOD DAY
Output :
62
Reading from text file
f=open(“student.txt”,’r’)

2. f. read(6) 🡪 reads only 6 bytes i.e 6 characters type – string


Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
a=f.read(10)
print(a) GOOD MORNING
GOOD EVENING
print(len(a)) GOOD AFTERNOON
f.close() GOOD EVENING
GOOD DAY
Output :
GOOD MORNI
10
f=open(“student.txt”,’r’)
3. f.readline( ) 🡪 reads only one line at a time.
Coding : student.txt
GOOD MORNING
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r") GOOD EVENING
a=f.readline( ) GOOD AFTERNOON
print(a) GOOD EVENING
b=f.readline() GOOD DAY
print(b)
print(type(a))
print(len(a))
f.close()
Output :
GOOD MORNING

GOOD EVENING

<class 'str'>
13
f=open(“student.txt”,’r’)
3. f.readline( ) 🡪 reads only one line at a time.
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
GOOD MORNING
a=f.readline( ) GOOD EVENING
print(a,end=‘’) GOOD AFTERNOON
b=f.readline() GOOD EVENING
GOOD DAY
print(b,end=‘’)
print(type(a))
print(len(a))
f.close()
Output :
GOOD MORNING
GOOD EVENING
<class 'str'>
13
Reading from text file
f=open(“student.txt”,’r’) GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
4. f.readline(8) 🡪 Reads only 8 bytes GOOD EVENING
GOOD MOR GOOD DAY
f=open(“student.txt”,’r’)

5. f.readlines( ) 🡪 Reads the entire content of the file line by line in list
Coding : student.txt
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r") GOOD MORNING
a=f.readlines( ) GOOD EVENING
print(a) GOOD AFTERNOON
GOOD EVENING
print(type(a)) GOOD DAY
f.close( )
Output :
['GOOD MORNING\n', 'GOOD EVENING\n', 'GOOD AFTERNOON\n', 'GOOD EVENING\n',
'GOOD DAY']

<class 'list'>
student.txtx

GOOD MORNING
f=open(“student.txt”,’r’)
GOOD EVENING
GOOD AFTERNOON
5. f.readlines( ) 🡪 Reads all lines and return them in list GOOD EVENING
GOOD DAY
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
a=f.readlines( )
print(len(a))
f.close( )
Output :

5
Reading from text file
f=open(“student.txt”,’r’) student.txt
GOOD MORNING
GOOD EVENING
6. f.readlines(4) 🡪 error
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
Split( ) function
>>> a="Have a nice day"
>>> b=a.split()
>>> print(b)
['Have', 'a', 'nice', 'day']
>>> print(len(b))
4
>>>
Program - 8
'''Python program to read a text file line by line and
display each word separated by a '#' '''

CODING :

file=open('C:\\Users\\user39\\Desktop\\practical1.txt','r')
lines=file.readlines()
for line in lines:
words=line.split()
for word in words :
print(word+"#",end="")
print("")
file.close()
Program - 8 - Output
SAMPLE RUN :

Like a joy on the heart of a sorrow.


The sunset hangs on a cloud.
A golden storm of glittering sheaves.
Of fair and frail and fluttering leaves.
The wild wind blows in a cloud.

OUTPUT :

Like#a#joy#on#the#heart#of#a#sorrow.#
The#sunset#hangs#on#a#cloud.#
A#golden#storm#of#glittering#sheaves.#
Of#fair#and#frail#and#fluttering#leaves.#
The#wild#wind#blows#in#a#cloud.#
Program - 9
'''Python program to read a text file and display the number of vowels/consonants/ uppercase/lowercase
characters in the file'''
CODING :
file=open('C:\\Users\\user39\\Desktop\\practical1.txt','r')
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower( )
if(ch in ['a,'e','i','o','u']):
vowels+=1
if(ch in ['b','c','d','f','g','h','j','k','l','m','n',
'p','q','r','s','t','v','w','x','y','z']):
consonants+=1
Program - 9 – Continuation
file.close()
print("Vowels are:",vowels)
print("Consonants :",consonants)
print("Lower_case_letters:",lower_case_letters)
print("Upper_case_letters:",upper_case_letters)
Program - 9 Output
SAMPLE RUN :

AI refers to Artificial Intelligence.


It is the intelligence of machines.
With AI, machines can perform reasoning and problem solving.
AI is the simulation of human intelligence by machines.
It is the fastest growing development in the world of technology.

OUTPUT :

Vowels are: 83
Consonants : 128
Lower_case_letters: 200
Upper_case_letters: 11
Program - 9
Reading from text file
f=open(“student.txt”,’r’) GOOD MORNING
1. f.read() 🡪 reads the entire content of the file byte by byte
GOOD EVENING
GOOD AFTERNOON
🡪 type - string
GOOD EVENING
GOOD MORNING
GOOD EVENING GOOD DAY
GOOD AFTERNOON
GOOD EVENING
GOOD DAY

2. f. read(6) 🡪 reads 6 bytes ( should not be given after read() function in coding ) – type - string
GOOD M
3. f.readline( ) 🡪 reads only one line at a time.
GOOD MORNING
a=f.readline( )
print(a,end="")
b=f.readline()
print(b)
4. f.readline(8) 🡪 Reads only 8 bytes
GOOD MOR
5. f.readlines( ) 🡪 Reads all lines and return them in list
['GOOD MORNING\n', 'GOOD EVENING\n', 'GOOD AFTERNOON \n‘,’GOOD EVENING\n’,’GOOD DAY\n’]
6. f.readlines(4) 🡪 error
WRITING ONTO TEXT FILES

There are two writing functions

1. write( ) 🡪 Write string to file

2. writelines ( ) 🡪 Write all strings in list form to file


WRITE ( )
Coding 1:
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt", "w")
f.write("Good Morning")
f.write("Good Evening ")
f.close()
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py ====
>>> |
NEW TEXT FILES

New file student1 will be created in


desktop
WRITE ( )
WRITE ( )
Coding 2 :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt","w")
f.write("Good Morning\n")
f.write("Good Evening ")
f.close()
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py ====
>>> |
WRITE ( )
WRITE ( )
Coding 3 :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt", "w")
f.write(“Praveen\n")
f.write(“Naveen")
f.close()
Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py ====
>>> |
WRITE ( )
Note : In Write mode previous
content will be erased and new
content will be added.
WRITE ( ) – using for loop
Coding 4 :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt", "w")
for i in range(5):
name=input("Enter the name of the student : ")
f.write(name)
f.close()
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py
====
Enter the name of the student : Ram
Enter the name of the student : Ravi
Enter the name of the student : Priya
Enter the name of the student : Raghul
Enter the name of the student : Rani
>>>
WRITE( ) – using for loop
Coding 4 : Output
WRITE ( ) – using for loop
Coding 5 :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt", "w")
for i in range(5):
name=input("Enter the name of the student : ")
f.write(name)
f.write(“\n”)

f.close()
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py ====
Enter the name of the student : Ram
Enter the name of the student : Ravi
Enter the name of the student : Priya
Enter the name of the student : Raghul
Enter the name of the student : Rani
>>>
WRITE( ) using for loop
writelines( )- To write the all the content together
Coding 1:
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt","w")
lst = [ ]
for i in range(5):
name=input("Enter the name of the student : ")
lst.append(name+"\n")
f.writelines(lst)
f.close()
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py ====
Enter the name of the student : aaa
Enter the name of the student : bbb
Enter the name of the student : ccc
Enter the name of the student : ddd
Enter the name of the student : eee
>>>
writelines ( )
Program – 10
'''Python program to remove all the lines that contain the character 'a' in a file and write it to another file '''
CODING :
file=open("C:\\Users\\user39\\Desktop\\practical1.txt","r")
lines =file.readlines()
file.close()
file=open("C:\\Users\\user39\\Desktop\\practical1.txt","w")
file1=open("C:\\Users\\user39\\Desktop\\practical2.txt","w")
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print("Lines containing char 'a' has been removed from pratical1.txt file")
print("Lines containing char 'a' has been saved in practical2.txt file")
file.close()
file1.close()
Program – 10 Output
OUTPUT :
Lines containing char 'a' has been removed from pratical1.txt file
Lines containing char 'a' has been saved in practical2.txt file
Program - 11
''' Write a python program to take a sample of ten phishing e-mails (or any text file)
and to find most commonly occurring word(s) in it.'''
CODING :
file=open("C:\\Users\\user39\\Desktop\\program12.txt","r")
content=file.read()
max=0
max_occuring_word=""
occurances_dict={}
words=content.split()
for word in words:
count=content.count(word)
occurances_dict.update({word:count})
if count>max:
max=count
max_occuring_word=word
print("Most occuring word is :", max_occuring_word)
print("No of times it occured is :",max)
print("Other words frequncy is :")
print(occurances_dict)
Program – 11 (output)

Output :
Standard Input, output and Error streams

⮚Standard input device ( stdin ) – reads from the keyboard

⮚Standard Output device ( stdout ) – Prints to the monitor

⮚Standard error device ( stderr ) – Display error on monitor if any


In python these standard streams are used with

sys module
Standard Input, output and Error streams
Coding 1:
import sys
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt“)
a=f.read() GOOD MORNING
GOOD EVENING
sys.stdout.write(a)🡪 Writes the data on the monitor GOOD AFTERNOON
GOOD EVENING
sys.stderr.write("\nNo errors Occurred\n") GOOD DAY
f.close()

BINARY ACADEMY MRS. GEETHA ROBIN M.SC.,M.PHIL.,M.ED ( COMPUTER SCIENCE )


Standard Input, output and Error streams
Output 1:
GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
No errors Occurred
>>> >>>
Standard Input, output and Error streams

import sys
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","w")
a=sys.stdin.readline() 🡪 Gets the data from the user
f.write(a) 🡪 Writes the same data on the file
f.close()
Standard Input, output and Error streams

>>>
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\
Python\Python39\prac.py ====
|Have a nice day
>>>
Have a nice day
with statement
f = open (“ student.txt ” , ” r ” )
…..
f.close()

----------using with open------------


with open (“ student.txt “, “ r “ ) as f :
a=f.read()
print(a)
-------------------------------------------------
Note : 1. Follow indentation
2. No need to close the file ( with statement will handle it )
Absolute and Relative Path
Absolute Path : The absolute paths are from the topmost level of the directory structure.
A Sample Directory Structure

E: \Accounts\History\cash.act E:\ ((root folder) the top most folder )


Project Sales Accounts

proj1 cl.dat proj2 Monthly Yearly Cash Bank History

main prg report prg jan sal mar sal yr1 sal yr2 sal cashac bankac

one bank two cpp

Relative Path : The relative paths are relative to current working directory denoted as a
dot(.) while its parent directory is denoted with two dots(..)

..\cl.dat ..\proj1\report.prg
Sta

S
MCQ – FILE HANDLING - TEXT FILE
Which of the following option is not correct?

a) if we try to read a text file that does not exist, an error occurs.
b) if we try to read a text file that does not exist, the file gets created.
c) if we try to write on a text file that does not exist, no error occurs.
d) if we try to write on a text file that does not exist, the file gets Created.
MCQ – FILE HANDLING - TEXT FILE
Which of the following option is not correct?

a) if we try to read a text file that does not exist, an error occurs.
b) if we try to read a text file that does not exist, the file gets created.
c) if we try to write on a text file that does not exist, no error occurs.
d) if we try to write on a text file that does not exist, the file gets Created.
Which of the following options can be used to read the first line of a
text file Myfile.txt?

a) myfile = open('Myfile.txt'); myfile.read()


b) myfile = open('Myfile.txt','r'); myfile.read(n)
c) myfile = open('Myfile.txt'); myfile.readline()
d) myfile = open('Myfile.txt'); myfile.readlines()
Which of the following options can be used to read the first line of a
text file Myfile.txt?

a) myfile = open('Myfile.txt'); myfile.read()


b) myfile = open('Myfile.txt','r'); myfile.read(n)
c) myfile = open('Myfile.txt'); myfile.readline()
d) myfile = open('Myfile.txt'); myfile.readlines()
Assume that the position of the file pointer is at the beginning of 3rd
line in a text file. Which of the following option can be used to read all
the remaining lines?

a) myfile.read()
b) myfile.read(n)
c) myfile.readline()
d) myfile.readlines()
Assume that the position of the file pointer is at the beginning of 3rd
line in a text file. Which of the following option can be used to read all
the remaining lines?

a) myfile.read()
b) myfile.read(n)
c) myfile.readline()
d) myfile.readlines()🡪 display in form of list
A text file student.txt is stored in the storage device. Identify the
correct option out of the following options to open the file in read
mode.
(i) myfile = open('student.txt','rb')
(ii) myfile = open('student.txt','w')
(iii) myfile = open('student.txt','r')
(iv) myfile = open('student.txt')

a) only i
b) both i and iv
c) both iii and iv
d) both i and iii
A text file student.txt is stored in the storage device. Identify the
correct option out of the following options to open the file in read
mode.
(i) myfile = open('student.txt','rb')
(ii) myfile = open('student.txt','w')
(iii) myfile = open('student.txt','r')
(iv) myfile = open('student.txt')

a) only i
b) both i and iv
c) both iii and iv
d) both i and iii
Suppose the content of “Essay.txt" is :-

Twinkle twinkle little star


How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star

What will be the output of the following code?

myfile = open("Essay.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[-2] in 'Rr':
line_count += 1
print(line_count)
myfile.close()

a) 2 b) 3 c) 4 d)5
Suppose the content of “Essay.txt" is :-

Twinkle twinkle little star


How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star

What will be the output of the following code?


f=open("C:\\Users\\ADMIN\\Desktop\\samp.txt","r",)
s=f.readline()
l=len(s)
print(l)
print(s[-2])
Output :
28
r
Suppose the content of “Essay.txt" is :-

Twinkle twinkle little star


How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star

What will be the output of the following code?

myfile = open("Essay.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[-2] in 'Rr':
line_count += 1
print(line_count)
myfile.close()

a) 2 b) 3 c) 4 d)5
Suppose content of 'Myfile.txt' is:

Twinkle twinkle little star


How I wonder what you are
Up above the world so high
Like a diamond in the sky

What will be the output of the following code?


myfile = open("Myfile.txt")
data = myfile.readlines()
print(len(data))
myfile.close()

a) 3 b) 4
c) 5 d) 6
Suppose content of 'Myfile.txt' is:

Twinkle twinkle little star


How I wonder what you are
Up above the world so high
Like a diamond in the sky

What will be the output of the following code?


myfile = open("Myfile.txt")
data = myfile.readlines()
print(len(data))
myfile.close()

a) 3 b) 4

c) 5 d) 6
Suppose content of 'Myfile.txt' is

Humpty Dumpty sat on a wall


Humpty Dumpty had a great fall
All the king's horses and all the king's men
Couldn't put Humpty together again

What will be the output of the following code?


myfile = open("Myfile.txt")
record = myfile.read().split()
print(len(record))
myfile.close()

a) 24
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is

Humpty Dumpty sat on a wall


Humpty Dumpty had a great fall
All the king's horses and all the king's men
Couldn't put Humpty together again

What will be the output of the following code?


myfile = open("Myfile.txt")
record = myfile.read().split()
print(len(record))
myfile.close()

a) 24
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is
Honesty is the best policy.
What will be the output of the following code?

myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()

a) 5
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is
Honesty is the best policy.
What will be the output of the following code?

myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()

a) 5
b) 25
c) 26
d) 27
Consider a file “TEST.txt” contains the following: What will be there in
the file after executing the coding
TEST.txt
Good Morning
Good Afternoon

def function ( ):
fin = open (“TEST.txt”, ‘w’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good Night
Good night Good night Good morning
Consider a file “TEST.txt” contains the following:
TEST.txt
Good Morning
Good Afternoon

def function ( ):
fin = open (“TEST.txt”, ‘w’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good
Night
Good night Good night Good morning
Consider a file “TEST.txt” contains the following: What will be there in the file
after executing the coding
TEST.txt
Good Morning
Good Afternoon

def function ( ):
fin = open (“TEST.txt”, ‘a’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good Night
Good Afternoon Good night Good morning
Good Night
Consider a file “TEST.txt” contains the following: What will be there in the file
after executing the coding
TEST.txt
Good Morning
Good Afternoon

def function ( ):
fin = open (“TEST.txt”, ‘a’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good Night
Good Afternoon Good night Good morning
Good Night
Suppose content of 'Myfile.txt' is
Culture is the widening of the mind and of the spirit.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()
a) 2
b) 3
c) 4
d) 5
Suppose content of 'Myfile.txt' is
Culture is the widening of the mind and of the spirit.
What will be the output of the following code?

myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()

a) 2
b) 3
c) 4
d) 5
Suppose content of 'Myfile.txt' is

Ek Bharat Shreshtha Bharat

What will be the output of the following code?


myfile = open("Myfile.txt")
vlist = list ( “ a e i o u A E I O U “ )
vc = 0
x = myfile.read()
for y in x:
if ( y in vlist ) :
vc + = 1
print(vc)
myfile.close()
a) 6
b) 7
c) 8
d) 9
Suppose content of 'Myfile.txt' is

Ek Bharat Shreshtha Bharat

What will be the output of the following code?


myfile = open("Myfile.txt")
vlist = list ( “ a e i o u A E I O U “ )
vc = 0
x = myfile.read()
for y in x:
if ( y in vlist ) :
vc + = 1
print(vc)
myfile.close()
a) 6
b) 7
c) 8
d) 9
Suppose content of 'Myfile.txt' is
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star
What will be the output of the following code?
myfile = open("Myfile.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[0] == 'T':
line_count += 1
print(line_count)
myfile.close()

a) 2 b) 3
BINARY ACADEMY c) 4 d) 5 MRS. GEETHA ROBIN M.SC.,M.PHIL.,M.ED ( COMPUTER SCIENCE )
Suppose content of 'Myfile.txt' is
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star
What will be the output of the following code?
myfile = open("Myfile.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[0] == 'T':
line_count += 1
print(line_count)
myfile.close()

a) 2 b) 3 c) 4 d) 5
Assume the content of text file, 'student.txt' is:
Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran
What will be the data type of data_rec?
myfile = open("Myfile.txt")
data_rec = myfile.readlines()
myfile.close()

a) string
b) list
c) tuple
d) dictionary
Assume the content of text file, 'student.txt' is:
Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran
What will be the data type of data_rec?
myfile = open("Myfile.txt")
data_rec = myfile.readlines()
myfile.close()

a) string
b) list
c) tuple
d) dictionary
Consider the following directory structure

Suppose root directory (School) and present working directory are the same. What will
be the absolute path of the file Syllabus.jpg?

a) School/syllabus.jpg
b) School/Academics/syllabus.jpg
c) School/Academics/../syllabus.jpg
d) School/Examination/syllabus.jpg
Consider the following directory structure

Suppose root directory (School) and present working directory are the same. What will
be the absolute path of the file Syllabus.jpg?

a) School/syllabus.jpg
b) School/Academics/syllabus.jpg
c) School/Academics/../syllabus.jpg
d) School/Examination/syllabus.jpg

You might also like