Q. How you will read a random line in a file using python?
A. We can read a random line in a file using a module named ‘random’.
For example:
import random
def read_random(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(read_random (‘hello.txt’)).
Q. Write a Python program to count the total number of lines in a text file?
A. def file_count(fname):
with open(fname) as f:
for i, 1 in enumerate(f):
return i+1
print(“Total number of lines in the text file: ”, file_count(“file.txt”))
Q. Tell me any 4 type conversions in Python?
A. int() – converts any data type into integer type
float() – converts any data type into float type
ord() – converts characters into integer
hex() – converts integers to hexadecimal.
Q. What is Dict and List comprehensions are?
A. They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.