Skip to Content

2 Ways to Skip a Line in Python

2 Ways to Skip a Line in Python

In this article will see how to skip a line in a file in Python. There are multiple ways to do that. In this post, we will discuss two approaches.

 

1. Using the readlines() method

The readlines() method reads a file and returns a list. Here, each item of a list contains a line of the file, i.e., list[0] will have the first line, list[1] the second line, and so on.

Since it is a list, we can iterate over it. When the current line number is equal to the line number that we want to skip, we omit that line. Otherwise, we consider it.

Consider the following example in which we print all lines, except the one that we want to skip.

 

def skipLine(f, skip):
  lines = f.readlines()
  skip = skip - 1 #index of the list starts from 0

  for line_no, line in enumerate(lines):
    if line_no==skip:
      pass
    else:
      print(line, end="")

 

Let’s try out the above code by skipping the first line of the sample.txt file.

 

sample.txt

This is a sample file.
Python is a very powerful programming language.
Let's see how to skip a line in Python.
It is very easy.
I love Python. It makes everything so fun.

 

try:
  f = open("sample.txt", "r")
  skipLine(f, 1) 
finally:
  f.close()

 

Output

 

Python is a very powerful programming language.
Let's see how to skip a line in Python.
It is very easy.
I love Python. It makes everything so fun.

 

Let’s now skip the 3rd line.

 

try:
  f = open("sample.txt", "r")
  skipLine(f, 3) 
finally:
  f.close()

 

Output

 

This is a sample file.
Python is a very powerful programming language.
It is very easy.
I love Python. It makes everything so fun.

 

If you pass a value that is greater than the total number of lines or less than 1, then nothing will happen.

 

2. Using the readlines() method and List Slicing

Since the readlines() method returns a list, we can perform slicing to skip a specific line. Consider the following example.

 

def skipLineSlicing(f, skip):
  skip -= 1 #index of list starts from 0
  if skip < 0: # if the skip is negative, then don't make any changes in the list
    skip= 1
  lines = f.readlines()
  lines = lines[0:skip] + lines[skip+1:len(lines)]
  for line in lines:
    print(line, end="")

 

Let’s skip the last line of the sample.txt file.

 

try:
  f = open("sample.txt", "r")
  skipLineSlicing(f, 5) 
finally:
  f.close()

 

Output

 

This is a sample file.
Python is a very powerful programming language.
Let's see how to skip a line in Python.
It is very easy.

 

Draw a triangle in Python
Previous
How to draw a triangle in Python
How to restart a program in Python
Next
How to restart a program in Python - Explained!