Text files worksheet in python
Text files worksheet in python
2 Write a Python statement to open a text file “DATA.TXT” so that new contents 1
can be written on it.
5 Which of the following statements is used to ensure that a file is automatically closed 1
after its operations are completed, even if errors occur?
(a) file.close( ) (b) try...except...finally
(c) with open(...) as file: (d) import file handling
6 What will be the output of the following Python code snippet if the file "my_file.txt" 1
contains the line "Hello World!"?
file = open("my_file.txt", "r")
content = file.read(5)
print(content)
file.close()
10 Write a function COUNTSIZE( ) in Python to read the file “POEM.TXT” and display
size of file. 2
OR
What is the output of the following code?
fh=file(“poem.txt”)
size=len(fh.read( ))
print(fh.read(5))
13 Write a user – defined function countH() in Python that displays the number 3
of lines starting with ‘H’ in the file ‘Para.txt”. Example , if the file contains:
Write a function countmy() in Python to read the text file “DATA.TXT” and
count the number of times “my” occurs in the file. For example , if the file
“DATA.TXT” contains –
“This is my website. I have displayed my preference in the CHOICE
section.” The country( ) function should display the output as:
“my occurs 2 times”
Q.No SECTION-D (1x 4 = 4 Marks) MARKS
14 a)Read the code and answer the question
fh=open(“main.txt”,”w”) 2
fh.write()
fh.close()
If the file contains “GOOD” before execution ,what will be the contents of the file
after execution of this code.
b)If a text file has contains the following data.predict the output of the code given 2
below
I SELL COMPUTERS.
I HAVE A COMPUTER.
I NEED A COMPUTER
fin=open(“data.txt”,’r’)
line=fin.readlines()
print(“Last line=”,line[-1])
Q.No SECTION-E (1x 5 = 5 Marks) MARKS
15 a)Write a function in python to count the number of lines in “POEM.txt” that begins 3
with an Uppercase character.
OR
Write a function in python to count the number of lines in a text file starting with
letter ‘A’
b)Complete the missing statement using for loop to print all the lines of file
f = open(“EMP.TXT”) 2
for ______________________ :
print(______)