Worksheet 1_SET C
Worksheet 1_SET C
Q2. Write a function count_lines() to count and display the total number of lines from the file
friend,txt.
Q3 Consider following lines for the file friends.txt 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("friends.txt")
l = f.readline()
l2 = f.readline(18)
ch3=f.read(10)
print(l2)
print(ch3)
print(f.readline())
f.close()
Answers
Q1. Fill in the blanks (Text file)
1. A collection of bytes stored in computer’s secondary memory is known as file.
2. File handling is a process of storing data into files and allows performing various tasks such
as read, write, append, search, and modify in files.
3. The transfer of data from program to memory (RAM) to permanent storage device (hard
disk) and vice versa are known as I/O operations.
4. A file is a file that stores data in a specific format on secondary storage devices.
5. In text files, each line terminates with EOL or ‘\n’ or carriage return, or ‘\r\n’.
6. To open file data.txt for reading, open function will be written as f = open("data.txt", "r").
7. To open file data.txt for writing, open function will be written as f = open("data.txt", "w").
8. In f=open(“data.txt”,”w”), f refers to file object.
9. To close file in a program, close() function is used.
10. A read() function reads the first 15 characters of the file.
11. A read(n) function reads most n bytes and returns the read bytes in the form of a string.
12. A readlines() function reads all lines from the file.
13. A write() function requires a string (File_Path) as a parameter to write in the file.
14. A writelines() function requires a sequence of lines, lists, tuples, etc., to write data into the
file.
15. To add data into an existing file, append mode is used.
16. A flush() function is used to write contents of the buffer onto storage.
17. A text file stores data in plain text or human-readable form.
18. A CSV (Comma-Separated Values) is a plain text file which contains a list of data in tabular
form.
19. You can create a file using open() function in Python.
20. A 'r+' symbol is used to perform reading as well as writing on files in Python.
Q2. Write a function count_lines() to count and display the total number of lines from the file
friends.txt.
def count_lines():
with open('friends.txt', 'r') as file:
lines = file.readlines()
print("Total number of lines:", len(lines))
count_lines()
Q3 Consider following lines for the file friends.txt 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("friends.txt")
l = f.readline()
l2 = f.readline(18)
ch3=f.read(10)
print(l2)
print(ch3)
print(f.readline())
f.close()