Advertisements
Advertisements
Question
Write a function to create a text file containing following data.
Neither apple nor pine are in pineapple. Boxing rings are square.
Writers write, but fingers don't fing. Overlook and oversee are opposites. A house can burn up as it burns down. An alarm goes off by going on.
- Read back the entire file content using read() or readlines () and display on screen.
- Append more text of your choice in the file and display the content of file with line numbers prefixed to line.
- Display last line of file.
- Display first line from 10th character onwards.
- Read and display a line from the file. Ask user to provide the line number to be read.
Code Writing
Advertisements
Solution
DATA = """Neither apple nor pine are in pineapple. Boxing rings are square.
Writers write, but fingers don't fing. Overlook and oversee are opposites. A house can burn up as it burns down. An alarm goes off by going on.
"""
def create_and_process():
with open("story.txt", "w") as file:
file.write(DATA)
# i) Read and display the complete file using read()
with open("story.txt", "r") as file:
print(file.read())
# ii) Append text and display numbered lines
with open("story.txt", "a") as file:
file.write("\nPractice makes programming better.\n")
with open("story.txt", "r") as file:
for number, line in enumerate(file, start=1):
print(number, line.rstrip("\n"))
# iii) Display the last line
with open("story.txt", "r") as file:
lines = file.readlines()
print("Last line:", lines[-1].rstrip("\n"))
# iv) Display the first line from the tenth character onwards
with open("story.txt", "r") as file:
first_line = file.readline()
print("From 10th character:", first_line[9:].rstrip("\n"))
# v) Read a line specified by the user
line_number = int(input("Enter line number: "))
with open("story.txt", "r") as file:
for number, line in enumerate(file, start=1):
if number == line_number:
print(line.rstrip("\n"))
break
else:
print("Invalid line number.")
create_and_process()shaalaa.com
Is there an error in this question or solution?
