Home / Programs / Write all content of a given file into a new file by skipping line number 5
🚀 Programming Example

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

👁 1,003 Views
💻 Practical Program
📘 Step Learning

Write a python program to create a new file from a existing file by skipping line number 5.

📌 Information & Algorithm

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

Given Input: Given test.txt file:

line1
line2
line3
line4
line5
line6
line7

Expected Output: Expected Output: new_file.txt

line1
line2
line3
line4
line6
line7

Hints:

  • 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

💻 Program Code

# 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
                        

🖥 Program Output

line1
line2
line3
line4
line6
line7
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.