A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

Write all content of a given file into a new file by skipping line number 5 using python programming
Q:

Write all content of a given file into a new file by skipping line number 5 using python programming

-1

Write all content of a given file into a new file by skipping line number 5

Create a test.txt file and add the below content to it.

Given test.txt file:

line1
line2
line3
line4
line5
line6
line7

Expected Output: new_file.txt

line1
line2
line3
line4
line6
line7

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  • Read all lines from a test.txt file using the readlines() method. This method returns all lines from a file as a list
  • Open new text file in write mode (w)
  • Set counter = 0
  • Iterate each line from a list
  • if the counter is 4, skip that line, else write that line in a new text file using the write() method
  • Increment counter by 1 in each iteration

Solution:

# read test.txt
with open("test.txt", "r") as fp:
    # read all lines from a file
    lines = fp.readlines()

# open new file in write mode
with open("new_file.txt", "w") as fp:
    count = 0
    # iterate each lines from a test.txt
    for line in lines:
        # skip 5th lines
        if count == 4:
            count += 1
            continue
        else:
            # write current line
            fp.write(line)
        # in each iteration reduce the count
        count += 1

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now