0% found this document useful (0 votes)
18 views10 pages

Adobe Scan 10-Sept-2024 4

The document contains a series of questions related to file handling in Python, specifically focusing on reading from and writing to text and CSV files. It covers various functions such as read(), readline(), and write(), as well as file modes like 'r', 'w', and 'a'. Additionally, it includes multiple-choice questions that test knowledge on file operations and the behavior of different file handling methods.

Uploaded by

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

Adobe Scan 10-Sept-2024 4

The document contains a series of questions related to file handling in Python, specifically focusing on reading from and writing to text and CSV files. It covers various functions such as read(), readline(), and write(), as well as file modes like 'r', 'w', and 'a'. Additionally, it includes multiple-choice questions that test knowledge on file operations and the behavior of different file handling methods.

Uploaded by

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

wTteinto CSVfiles using the writerow() function

witerows()function., 6. Which function is used to read a single line


from a file?
Reading from CSV files :
cSV.reader())- Returns a reader object. (a) readline)
Itloadsthe data from CSV file into an iterable after (b) read()
parsingdelimiteddata (c) readlines()
(d) readfulline)
7. What would be the datatype of variable data
in the following statements?
Scan this QR Code (a) Data = f.read ) -- string
For Video (b) Data = f. read (10) -- string
Explanation of (c) Data = f. readline ()-- string
list
# File Handling (d) Data = f.readlines ( ) --
8. Which function is used to write all the
characters?
(a) write)
(b) writeall()
Objective Type Questions (c) writechars()
(d) writechar()
Text Files 9. Which of the following is not a valid mode to
open a text file?
1. What is the default mode to open a text file? (a) ab /
(a) r / (b) rt
(b) W (c) wt
(c) a (d) r
10. Which of the following mode in file opening
(d) rt statement results or generates an error if the
2. To open a file C:\test.txt for appending data,
file does not exist? CBSE Sample Paper (2022-23)
we use:

(a) File = open ("C:\\test. txt", "a") (a) a+


(b) r+ /
(b) File = open ("C:\\test. txt", (c) wt
"rw") (d) None of the above
11. What is the difference between rt and w+
(c) File = open(r"C:\test. txt", "a") modes?
(a) No difference
(0) File = open ("C:\\test.txt") (b) In r+ mode, the pointer is initially placed at the
J. To read the next line of the file from a file
beginning of the file and for w+, the pointer is
object infi, we use: placed at the end.
(a) infi.read (all)
(b) infi.read () (c) In w+ mode, the pointer is initially placed at the
beginning of the file and for t, the pointer is
() infi.readline () placed at the end.
(d) infi.readlines () (d) In case of r+ mode, if file not exists it will raise
t The readlines()method returns : an error. Whereas in w+ mode, it will create a
(a) str
new file, if it does not exist.
(b) Alist of lines (e) Depends on the Operating system.
(©) Alist of single characters 12. Which of the following statements are true
(d) Alist of
integers.
5, Which function is used to read all characters? regarding the opening modes of a file?
(a) When you open a file for reading, if the file
la) read () doesn't exist, an error occurs.
(b) readall)
(c) readchars() (b) When you open a file for writing, if the file
doesn't exist an error occurs.
(d) readline)
(c) When you open a file for reading, if the file does
not exist, the program will open an empty file.
Question bank -Class XIl (Computer Science)
By Swati Chawla
59
the
What will bethe output of
(d) When you open a file for
exist, a new file will be
(e) When you open a file
writing, if it
created. /
does not myfile = open("Myfile.txt")
data = myfile.readlines()
fol owing code?
exists, the existing file isfor writing, if the file print(len(data)
new file. overwritten with the myfile.close() CBSE Sample
Paper
13. The other name of
file object is file handle.
14. Toclose an open file,
15. To read all the file close method isused.
contents in the form of a list,
Ans. 4
23. Suppose content of Myfile.txt? is
Humpty Dumpty sat on a wall
(2021-22)
readlines()
16. Write method is used.
a python Humpty Dumpty had a great fall
statement to open a text file Allthe king's horses and all the king's men
STORY.txt in read
mode. "r")
Ans. f=open("STORY.txt", Couldn't put Humpty together again
17. Write a What will be the output of the
BOOK.txt"
statement in Python to open a
to write the new file myfile = open("Myfile.txt") following code?
as well as content in a file record = mnyfile.read().split()
preserving the old
Ans. f-open("BOOK.txt", "a")content.
18. To read 2 print(len(record))
the command characters from a file object fobj, myfile.close) CBSE Sample Paper (2021-22)
should be: a. 24
(a) fobj .read (2) b. 25
(b)
(c) fobj.read() c. 26
(d)
fobj.readline () d. 27
fobj.read2 ()
19. Observe the following code and answer 24.
Consider the following directory
questions that follows the structure. CBSE Sample Paper (2021-22)
File = open ("Mydata" , "a")
# Statement1 School
File close ()
(i) What type of file is
Text File Mydata (Text / Binary)? |Academics
(iü)Fill in the OExamination Sports

Statement1 to write ABC" in file Syllabus.jpg


Mydata. Result.png ElAchievement.jpg
File.write("ABC")
20. Read the code gjven below and answer the Suppose root directory (School) and
questions. working directory are the same. Whatpresent
will be
F1 = open ("Story. txt" "w) theabsolute path of the file
F1.write ("BYE")
F1.clOse ()
a. School/syllabus.jpg
b. School/Academics/syllabus.jpg
Syllabus.jpg?
If the file Story.txt contains c. School/Academics/../syllabus.jpg
GOOD" before
execution, what will be the contents of the file d. SchoolVExamination/syllabus.jpg
after execution of this code.
Ans. BYE
21. What is the output of the Binary Files
1.
Fl=open ("testl.tt"following code? Which of the
Size = len (Fl.read () ) "r") write the data following
in
function do you use to
print ( £1. read (5) ) (a) write ( ) the binary format?
£1.close () (b) output ()
Ans. No Output (c) load ()
22, (d) dump ( )
Suppose content of 'Myfile.txt' is: 2. To read
and module
Twinkle twinkle little star of Python is write into binary files, pickle
The absolute used.
How Iwonder what you are 3. levelof
Up above the world so high paths are from the topmost
Like adiamond in the sky the directory structure.
(True/False) --True
Question bank - Class XIi(Computer Science)
By Swati Chawla
By DunZoAns. opened Ans. code.the Fl eXcept: at before ry: 7 6
atiuestion U the 0 (b) mentioned(aT)he 6
print(|D[S]) fin.close)
pickle.dump(ID,fin)
-pickle.load(fout)
Tout-open(*Emp.dat", Import What
"rb`) 5:"Dunzo"} pickle in whiTrue:lfie n-open( piimcporklte a
Following ItThe ent. t with The
inFopen("Emp.dat", Correction the exact file wil Cont wil WhenthfeilAnse .
Class
bank DF{:Nisha", Lin-pos
e Line 1 in fin.close() ifreading ap enmo
d de
rb wb
klet netipfeycrfklothreminsg.pickling. diThrewoectrk(oiTnrelgryuae.tiTvhee
add dat a=['one',2,(3,4]im|piporIcdunpi
wil 2 + blanks Stu['location
M arks' Marks']
Stu['}+=3 Stu-pickle.load(fin) "Stu. opened mentioned create
pickle.dump(data,)
open("dataz. dat",
(in "rb
load
- Pickle.dump(Stu,fin) the = code the
dump(True
be - mode.
f.seek dat", opened
binaryfor line () ()
the in in fin.tell) with data a function pathsare
Xl of
code record. "rb") iS file file file(ab), 3) /
output(pos) Line t#Line
he Written code. function
in Fal Falsse)e
uter 2:"53050", in the from does that
with does
"wb") record.[92,93,94]: #Line what is the(True
False /
of
Line : and 1 2: following the exist. not
-- of
pickle relativeto
/False)
toend happens following
the 2: Line Place 1 update name as of
cience) 3: Store : exist. False)
File of f: pickle module --
"IT",4:following 2 the code: the and
to file a when: -- True the
shouldcomplete file record file. writesthe output
pointer position module performs current
"38" code:
be in in
61

20. 19. 18. Output


de bytes
Ans. 17. (d) (c) (b) (a) Fp.pos
16.Fp.loc()
(d) ()(c) Fp.seek
(b) (a) () 15. (d) (c) (b) (a) 14. lo. argument12. 11.is
characters.
Help location object.
F.seek
Ans. (0) File Statement 2.print ItFile File method?
seek()
the IT --
the a
Ans. that.
wifp.seek(-10,
l
en("data.txt",rt")Observe 1) charactersbackwardfromNisha statement File What Fp.seek
Fp.tell currentWhich None (True
Fp.seekpointerWhichDeginning
Fp.seek The file.seek
beginning Neha Statementl Explain (-3,2) F=open("Test.txt",w+")
F.seek Considerresults
F.wbackward
rite("0123456789abcdef") the True
be Assume her (F.read pointerpointerpointer number offset
intends happens of /False) second method
print(fp.rthead(13)
e wants )
position (offset,(offset to
statement
to and Statement the in statementthese(offset an of
output? the for of from an
remains is is file of
write
fp is set set offset argument
- bytes
following then to the a to (2)) followingerror if , Falsewould used to
is position the used to to no within I), 2) 0)
the the move same text Statement
/ /1 the the is
value
she end. toStatement I unchanged.V is used
to of
file
correct move
and code: start
endarguments the used be of be seek random
code wants the assuming file. the of of from to taken seek moved.
()
pointer. give file? ()
file
file the 2
the the to the
change as is method access
carefully. statement(s) current
Write the file. file. are seek
to the pointer file retrieve start? set (True
pointer "F" passed of
read pointer output e
to indicates
thposition.
Python 2,False) / data
What is to file then
the the to the in
for 13 10 3 of
F.f.write
wf.close()
rite(("xyz8466")
"0123456789abcdef") (c) omit()
(d) bounce()
3. A CSV file is also known as a
f.seek(0) (a) Flat File /
f.read() (b) 3D File
Ans.Try to do it yourself (c) String File
Hint : fclose () -- (d) Random File
21. Observe the
write the outputfollowing code carefully and 4. Which of the following module is
provi
csv dfiles?
ed
of the following, Pythonto do several operations on
flfl.write("Make
=open(r"'e:\fl1theit.txaworld")
fl.write("Heal t"special
"w") place") (a) pickle
(b) csy
fl.write("For uand for me") (c) os
(d) CSV
fl.write("And
f1.close()
the entire human
race") 5. What is the output of the
following program?
import csv
flprint(rl)
2-open(r'e:\fl .txt","r")
rl=f12.read(5) d=csv.reader (open('c:\PYPRG\ch13
\city.csv'))
next (d)
r2-f12.read(15)
print(r2) for row in d:

fl2.seek(2) print (row)


r3-f12.read(8)
print(r3) If the file called
city.csv contain the
r4-f12.tell) following details:
print(r4) Chennai, Mylapore
f12.seek(15) Mumbai, Andheri
(a) Chennai,mylapore
r5=f12.tell) (b) Mumbai,Andheri
print(r5)
f12.seek(20) (c) Chennai
Mumbai
r6-f12.read(10) (d) Chennai,Mylapore
print(r6)
r7-12.tell(
print(r7)
Mumbai,Andheri
6. To specify a different delimiter while
a csv file, delimiter writing into
print(fl2.read)
Ans. csv.writer. argument is used with
Heal 7. The CSV files
can only take comma G) 25
the worldMake i
al the w
delimiter.
8. The CSV (True/False) -- False
files are text files.
10 True (True/False)
15 9. cSy format is a text format,
accessible to a
ta specia
10.
applications across several platforms.
30 /mport esv statement is given for
l placeFor u and for meAnd the entire
human race module into your program. importing
CSV Files 11. Comma is the default delimiter for a CSV file.
1. What does CSV stand for? (True/False) -- False
12. To
(a) Cursor Separated Variables read the data
of csv module is from a csv file reader
function
(b) Comma Separated Values
(c) Cursor Separated Values 13. CSV files are used.with
open newline argument to
(d) Cursor Separated Versions. suppress EOL translation.
14. For reading data from a CSV file, CSV.reader )
2. The function used to skip a row
in a csv file
is.... loads the data from the cSv file, parses it and
(a) nextO makes it available in the form of an iterator
(b) skip() wherefrom the records
row. can be fetched row by

Question bank - Class Xl(Computer Science) 62


By Swati Chawla
Identifythe error in the following code: open a text file
import csv 4. Write a statement in Python to be added
fzopen('attendees1 . csv') STORY.txt so that new contents can
(£) at the end of a file.
csV f=cSv. Writer Ans. F= open ("STORY. TXT", "a)
Ans. Thefile must be opened in wmode in Line open a text file
5. Write a statement in Python tocontents can be
2 CONTENT.TXT so that new
ldentifythe error in the following code: written in it.
import csv "w")
Ans. F =open ("CONTENT.txt", open a text file
f=open( 'attendees2 . csy') 6. Write a statement in Python to can
csV f=CSv.
reader( ) REMARKS.TXT so that existing content
for roW in cSv f: be read from it.
print (row) "r")
Ans. F = open (REMARKS.txt", pointer to the
Ans. CSV f=csv.reader ((f) position the file
7. Nancy intends to Write Python statement for
Assertion (A): CSV (omma Separated beginning of atext file.
17. Fileobject.
Values) isaafile format for data storage which the same assuming F is the
lookslike atext file. CBSE Sample Paper (2022-23)
Ans. F.seek(0)
Reason(R): The information is organized with 8.Observe the following code
and answer the
one recordon each line and each field is questions that follow
separated by comma. CBSE Sample Paper (2022-23) File = open("Mydata","a")
correct #Blankl
lo) Both A and Rare true and Ris the
explanationfor A / File.close)
of file is Mydata?
b) Both A and R are true and R is not the
correct i.What type (Text/Binary)
statement to write ABC"
explanation for A ii. Fillthe Blank1with
in the file Mydata".
False
(c) Ais True but R is Ans: i. Text File
ii. File.write("ABC")
(d) Ais false but R is True "file modes
(Solved) 9. Differentiate between w" and
Practice Ouestions of Text Files perform the used in Python while opening
a data file.
1.Write a statement in Python to using suitable
following operations: Illustrate the difference
BOOK.TXT" in read Compartment, 2020
(a)To open a text file
examples.
write content
mode. Ans. A file is opened using w" mode to mode to read
r"
Ans. F1= open
(BOOK.TXT", "r") into the file. A file is opened using
BOOK.TXT" in write content into the file.
(b)To open a text file
mode. Example:
"w")
Ans. F2 =open (B0OK.TXT",modes rt and w+ def Create ()):
file file=open('NOTES. TXT',w')
2. Differentiate between
witch respect to Python. , We Can S=This is a sample"
Ans. In both the modes , i.e. rt and wt read from £ile.write (S)
can
perform both the operations. Wemain difference
But the file.close ()
afile and write toa file.
opening a file in rt mode , the
IS that , if we are otherwise it will show def Read () :
Ile must exists before , not necessary £ile=open('NOTES. TXT','r)
eITOr. Whereas in wt mode, it's not exists,
drive. Ifit's
that our file exists in hard Lines=file,readline();
It will create the file with that name.r+ and rb+ print (Lines)
3. between file modes
Differentiate
with respect to Python.
file.close ()
Ans r+ Opens afile for both reading and writing. The 10. Write a method in python to read the
content
of the file. rb+
e pointer placed at the beginningwriting in binary
from a text file diarv.txt line by line and
Upens afile for both reading and beginning of display the same on the screen.
format. The file pointer placed at the Ans.
the file. def LinesCount () :

63
bank - Class Xl (Computer Science)
ByQuestion Chawla
Swati
F=open ("diary.txt", "r") data=F.readlines ()
strl=! Count=0
while strl: for lines in data:
strl=F. readline ()
print (str1, end=!')
line-lines. split)
for wOrd in line :
F.close ()
11. Write amethod in
if WOrd==" India!.
lines of text contentsPython to write
into a text file multiple
Count =

Ans,
line. myfile.txt
print (Count)
F.close( )
Count t1

def Addline (): 15. Write a method/function


F=open ("myfile.txt", "w")
while True :
Python to read contents from a
CODE.TXT, to count and textBIGWORDSO in
:") Line=input ("Enter a line
0Ccurrence of
or more alphabets.
those words, which
are displhaviay ngthe3
F.write (Line) For example:
If the content of the file is :
F.write ("\n") ME AND MY
lines Choice=input
(Y/N) ?") ("Enter more FRIENDS ENSURE SAFETY
AND SECURITY OF EVERYONE
if Choice in "Nn": The method/function should display
break Count of big words is 5
12.
F.close( ) Ans.
Write a method in Python to read def BIGWORDS():
from a text file lines F=open
DIARY.TXT,
lines, which are starting with an
and display those ("code.TXT", " r")
data=F.readlines ()
alphabet 'P'. Count=0
Ans. for lines in
def PLINES (): data:
file-open line=lines.split ()
lines = ('myfile TXT', 'r)
. for word in
line:
file.readlines
for w in lines:
) if len
(word) >=5:
if w[0]=="p": Count = Count + 1
print ("Count of big
words ",Count)
16. F.close()
print (W, end=!)
file.close () Write a
pythonmethod/function
13. Write a
python to readmethod/function ABLINES) in in to read lines SHORTWORDS0
contents from from a text ie
LINES.TXT,
a text file
to display those lines,
which are
WORDBANK. T XT, and
which arelesser than 5 display those words,
either starting with an alphabet A' or Ans. characters.
with alphabet B'. starting def
Ans.
def ABLINES (): SHORTWORDS
F=open
() :

F=open ("LINES. TXT", "r") ("WORDBANK. ()TXT", "r")


data-F.readlines
Lines=F.readlines () Count=0
for
for W in Lines: lines in
if W[0] =="A" data:
"B":

F.close ()
print (W, end=!)
Or
W[0]==
line=lines.split)
for word in
line:
if len (word) <5:
14.
Write a method in Python to print ("Count Count=Count+1
of Small words
from a text file INDIA. read lines
TXT,to find and display
the occurrence of the word
",Count)
Ans, $India". 17. WriteF.close(
a
def CountIndia(): Python to metreadhod/funct ion BIGLINES) IO
file
lines from a textlines
F=open (" INDIA.
Question bank - Class XIl (Computer
By Swati Chawla
TXT", "r")
Science) 64
CONTENT.TXT, and
Ans. which are bigger than 20 display
those

characterS.
defBIGLINES):
(
T or t
F-open("ccontent.TXT", "r") Print ("The number of
data=F..readlines () :",T)
for line in data: f.close()
if len (line)>20: ETCount ()
toread lines from a
print (line, end=!') 0 Writea method in Python
and count those lines,
F.close () text file NOTES.TXT,
BIGLINES() which are ending with .' or ';
method/function ISTOUPCOUNTO Ans. Try to do yourself the
Vritea to count
21. Write a function in python STORY.TXT"
pytthonto read contents from a text file file
in
WRITER. TXT, to count and display the number of lines in a text
'A'.
oCCurrenceoffthe word IS» or TO" or UP". which is starting with an alphabet

ef
Ans. ISTOUPCOUNT(): Ans:
def COUNTLINES () :
'r')
c=0 file=open ('India. TXT',
file=open(India.TXT', 'r) lines =
file.readlines ()
line = file. read () count=0
wOrd = line.split () for w in lines :
for w in word: if w{O]=="A" or w[0]== "a":
if w=="IS" or w=="TO" or w=="UP": count=count+1
c=c+1 print("Total lines:",count)
print("Count of lS, TOand UP is ".c) file.close ()
file. close () COUNTILINES()
ISTOUPCOUNT ()
DISPLAYWORDSO
Write afunction ETCount) in Python, which 22. Write a method/function
lines from a text file
file
should read each character of a text in python to read which
uTESTFILE2.TXT and then count and STORY.TXT, and display those words,
alphabets are less than 4 characters.
display the count of occurrence of
Eand Tindividually (including smallcases e Ans. Try to do yourself () the following
and t too). CBSE Sample Paper (2022-23) 23. A text file Quotes.Txt" has
data written in it:
Example:
If the file content is as follows: Living a life youcan be proud of
Doing your best
activities
Today is a pleasant day. Spending your time with people and
that are important to you Standing up for
It might rain today. hard
things that are right even when it's
It is mentioned on weather sites Becoming the best version of you
Write a user defined function to display the
Ihe ETCount) function should display the total number of words present in the file.
output as:
The number of E or e: 6
Ans:
Ihe number of Tor t:9 def COUNTWORDS () :
c=0
file=open ('Quotes. txt', 'r')
tef
ETCount () :
Open ("testfile2. txt", "r")
line = file. read()
word = line. split()
data=f, read() for w in word:
E=T=0
tor i
C = c + 1
in data: print ("Total number of Words :
if i in 'Ee':
", c)
E+=1
if i in 'Tt': 24. Write a function Show words) in python to
T+=1 read the content of a text file 'NOTES.TXT"
print ("The number of E or e and display the entirecontent in capital letters.

65
sion nbank -Class XIl (Computer Science)
Swgi Chowlo
Example, if the file contains: "This is a test Lines = file. readlines()
file" for L in Lines:
Then the function should Compartment, 2020 W=L.split ()
as: THIS IS A TEST display the output if (len (W) ==5):
FILE print (L, end=)
Ans. #Method 1 file.close ()
def Show words (): Show words ()
file-open ('NOTES. TXT', 'r) 26. Write afunction countmy( )in Python to
Lines =
for L in file.readlines ()
the text file DATA.TXT"
and count rethade
number of times "my" occurs in the fle
Lines:
print (L.upper(),end=") For example if the file "DATA.TXT"
file.close ()
Show words ()
This is my website. I have
preferences in the CHOICE section,
The countmy( ) function should
displayedcontains,
#Method 2 output as: display the
def Show words (): "my occurs2 times".
Ans:
file=open ('NOTES. TXT', 'r')
L = def countmy () :
file.read ()
print (L.upper ())
f = open ('DATA. txt', 'r
Count = 0
file.close () x = f . read()
Show words () word = X . split ( )
25. Write a function Show for i in word :
read the content of a textwords) in python to
file 'NOTES.TXT" if ( i == 'my') :
and display only such lines of the file Count =Count + 1
have exactly 5 words in them. which
print ('my occurs' Count
Example, if the file contains: Itimes')
"This is a sample file. 27. Atext file "Quotes.Txt" has the
The file contains many data written in it: following
But need only sentencessentences.
which have only 5 Living a life you can be proud of
Words. '" Doing your best
Then the function should display the Spending your time with people and activities
output
as:
Compartment, 2020 that are important to you
This is a sample file. Standing up for things that are right even when
The file contains many it's hard
sentences.
Ans. #Display those lines having 5 Becoming the best version of you
WOrds. Write a user defined function
#Method 1 total number of words present intothedisplay the
def Show words () : Ans. file.
def
line= ! Words () :
f=open ("Notes.txt", "r") f=open ("Quotes.txt", "r")
while True: L=f.read ()
if line==!: Count=0
else:
break words=L.split
for i in
()
words:
line=f.readline () Countt=1
Words=line.split () print ("Total nunber of wordD
if len (words) ==5: :"Count)
28. Write a
print (1ine, end=") method in Python
text file Poem.txt" to read
and display
lines from
those words ,
Show words ()
#Method 2 which are ending with 'e.
Ans:
def Show words():
file=open ('NOTES. TXT','r') def read() :
f=open ("Poem. txt", 'r')
Question bank - Class XIl (Computer Science) 66
By Swati Chawla
k=f.read()
did not
s=k.split() there was too much crowd, which she
s:
for 1 ln like.
if i[-1] =='e': visit some hill
So thistime she decided toCompartment, 2021
print (i, end=! ) station.
f.close()
Writea method in Python to read lines from Ans.
atextfile Story.txt" and calculate and display #Method 1
thesumof allIthe even digits present in a text def ChangeGender () :
I=open ("BIOPIC. TXT", 'r')
file
Text=f.read ()
'," she
sefread(): Print (Text.replace (! he
f-open ("PoemDigit.1txt", 'r') ))
s=0 f.close ()
k=f. read ()
for i in k: #Method 2
if i.isdigit ():
def ChangeGender () :
if int(i)%2==0: 'r')
With open ('BIOPIC. TXT',
S=s+int (i) as File:
print (s) Lines = File.readlines
()
f.close () for L in Lines:
M a function Remove_Lowewrcase) that
Write Words = L.split ()
srcepts two file names, and copies all the lines for W in Words:
thaf do not start withlowercase letter from the if W == 'he':
first file into second file. W = 'she!
Ans.
(): print (W, end = ! )
isf Remove LowerCase print ()
f=open ("Poem. txt", "r")
p=open ("Poeml.txt", "w") ChangeGender )
x=f.readlines () 32. Write the definition of a function
for i in x: CountLine() in Python, which should read
if i[0].islower (): each line of a text file "SHIVAJI.TXT" and
continue count total number of lines present in text
else: file.
p.write (i) For exanmple, if the content of the file
"SHIVAJI. TXT" is as follows :
f.close ()
p.close() Shivaji was born in the family of Bhonsle.
He was devoted to his mother Jijabai.
Write the definition of afunction India at that time was under Muslim rule.
ChangeGender() in Python , which reads the
Contents ofa text file "BIOPIC.TXT" and The function should read the file content and
display the output as follows :
isplays the content of the file with every Total number of lines : 3
currence of the word he' replaced by 'she'. Compartment, 2021
For example, if the content of the file Ans.
"BIOPIC. TXT" is as follows: def Count Line () :
Last time he went to f=open ("SHIVAJI. TXT", 'r')
Agra,
there was too much crowd, which he did not Lines=f.readlines ()
ike, print('Total number of lines :',
So this time he decided to visit some hill len (Lines) )
f.close ()
Station. Count Line ()
The function should read the file content and
33. Write a method/function
isplay the output follows:
Last DISPLAYWORDSO in python to read lines
time she went to
Agra,
n 67
bank - Class SXl (Computer Science)
Nti Chowa
from a text file
STORY.TXT,
those words, which and display
are less than 4
(
characters.
CBSE Sample Paper (2019-20)
Ans.
def DISPLAYWORDS ():

file=open(STORY.TXT'
line = file.read() ,' )
word = line. split()
for w in wOrd:
if len (w) <4:
print ( w)
file.close ()
34. Write a function in python to
count the
number of lines in a text file STORY.TXT
which is starting with an alphabet A'
Ans.
CBSE Sample Paper (2019-20)
def COUNTLINES ():
file=open('STORY. TXT', r')
lines = file.readlines ()
Count=0
for w in lines:
if w[0]=="A" or w[0]=="a":
Count=count+1
print ("Total lines",count)
file.close ()
Draoico Ouetions of Rinary Files

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy