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.
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.
sample.txt
To skip the first line in Python, use this code:
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
You can also skip lines in Python using the readlines() function 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.
To skip the last line of a file in Python (in our case sample.txt), use this code:
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.
Hey guys! It’s me, Marcel, aka Maschi. On MaschiTuts, it’s all about tutorials! No matter the topic of the article, the goal always remains the same: Providing you guys with the most in-depth and helpful tutorials!