Q1 . Write a Python program to read an entire text file.
Code :
def read_text(Myself):
with open(Myself,'r') as f:
return f.read()
print(read_text("/content/sample_data/Myself"))
output :
Q2. Write a Python program to read first n lines of a file.
Code:
def read_n_lines(Myself, n):
with open(Myself, 'r') as file:
return [file.readline().strip() for _ in range(n)]
print(read_n_lines("/content/sample_data/Myself ", 3))
Q3. . Write a Python program to append text to a file and
display the text.
Code:
def append_text(Myself, text):
with open(Myself, 'a') as file:
file.write(text + '\n')
return read_file(Myself)
print(append_text("/content/sample_data/Myself ", "\n I
have cleared all the subjects in Sem 1."))
output:
Q4. Write a Python program to read last n lines of a file
Code:
from collections import deque
def read_last_n_lines(Myself, n):
with open(Myself, 'r') as file:
return list(deque(file, n))
print(read_last_n_lines("/content/sample_data/Myself ", 1))
output:
Q5. Write a Python program to read a file line by line and store it into a
list.
Code :
def file_to_list(Myself):
with open(Myself, 'r') as file:
return [line.strip() for line in file]
print(file_to_list("/content/sample_data/Myself "))
Output :
['My Name is Nakshi Shah', 'roll no: 50', 'Div: I', 'Batch: I3', 'Branch:
EXTC', '', 'I have cleared all the subjects in Sem 1.']
Q6. Write a Python program to read a file line by line store it into a
variable.
Code:
def file_to_variable(Myself):
with open(Myself, 'r') as file:
return file.read()
print(file_to_variable("/content/sample_data/Myself "))
Output:
My Name is Nakshi Shah
roll no : 50
Div: I
Batch: I3
Branch: EXTC
I have cleared all the subjects in Sem 1.
Q7. Write a Python program to read a file line by line store it into an
array.
Code:
def file_to_array(Myself):
return file_to_list(Myself)
print(file_to_array("/content/sample_data/Myself "))
Output:
['My Name is Nakshi Shah', 'roll no: 50', 'Div: I', 'Batch: I3', 'Branch:
EXTC', '', 'I have cleared all the subjects in Sem 1.']
Q8. Write a python program to find the longest words.
Code:
def find_longest_word(Myself):
return max(open(Myself).read().split(), key=len)
print(find_longest_word("/content/sample_data/Myself "))
Output: Subjects
Q9. Write a Python program to count the number of lines in a text file
Code:
def count_lines(Myself):
with open(Myself, 'r') as file:
return sum(1 for line in file)
print(count_lines("/content/sample_data/Myself "))
Output: 7
Q10. . Write a Python program to count the frequency of words in a file.
Code:
from collections import Counter
def word_frequency(filename):
with open(filename, 'r') as file:
return dict(Counter(file.read().split()))
print(word_frequency("sample.txt"))
Output: {'My': 1, 'Name': 1, 'is': 1, 'Nakshi': 1, 'Shah': 1, 'roll': 1, 'no': 1, ':':
4, '50': 1, 'Div': 1, 'I': 2, 'Batch': 1, 'I3': 1, 'Branch': 1, 'EXTC': 1, 'have': 1,
'cleared': 1, 'all': 1, 'the': 1, 'subjects': 1, 'in': 1, 'Sem': 1, '1.': 1}