मराठी

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.

Advertisements
Advertisements

प्रश्न

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.

  1. Read back the entire file content using read() or readlines () and display on screen.
  2. Append more text of your choice in the file and display the content of file with line numbers prefixed to line.
  3. Display last line of file.
  4. Display first line from 10th character onwards.
  5. Read and display a line from the file. Ask user to provide the line number to be read.
कोड लेखन
Advertisements

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 7: Data File Handling - EXERCISE [पृष्ठ १४६]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 7 Data File Handling
EXERCISE | Q 14. | पृष्ठ १४६
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×