Write all content of a given file into a new file by skipping line number 5
Write a python program to create a new file from a existing file by skipping line number 5.
Write a python program to create a new file from a existing file by skipping line number 5.
Create a test.txt file and add the below content to it.
line1 line2 line3 line4 line5 line6 line7
line1 line2 line3 line4 line6 line7
readlines() method. This method returns all lines from a file as a listw)counter = 0write() method
# 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
line1
line2
line3
line4
line6
line7
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.
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.