Home > database >  How to igore a line when using readlines in python?
How to igore a line when using readlines in python?

Time:02-22

a=open('D:/1.txt','r')
b=a.readlines()

now we get b which contains all the line in 1.txt.
But we know that in python when we don't use a line we could use

\# mark

to igonore the specific line.
Is there any command we could use in TXT to ignore a specific line when use readlines?

CodePudding user response:

Text files have no specific syntax, they are just a sequence of characters. It is up to your program to decide if any of these characters have particular meaning for your program.

For example if you wanted to read all lines, but discard those starting with '#' then you could filter those out using a list comprehension

with open('D:/1.txt','r') as a:
    lines = [line for line in a if not line.startswith('#')]

CodePudding user response:

Just made a quick google search and found a working code, I am going to quote the author:

It is very easy to do it. You can get exact number of lines by using len() function. So, if you know which line is that you can skip. Otherwise, if there is a specific line you would like to take out you can do that without using external regex by just using in statement.

This is how it looks like:

Code for printing each line:

for line in file_: 
    print (line) 
 

Output:

fdadsfdsa 
lllllll 
pppdsa 

Code for getting length of file:

len(file_) 

Output:

17 

Code splitting lines and adding to buffer (lines with "ll" will not be read):

with open('file.txt', 'r') as file_: 
    file_ = file_.read().splitlines() 
 
buff = '' 
for line in file_: 
    if 'll' in line: 
            continue 
    else: 
            buff = buff   '\n'   line 
 
print (buff) 

Output:

fdadsfdsa 
pppdsa 

In your case you can make a counter, and when the number of line you do not want to read arrives do the same as in the code above and go into an if with continue inside.

credits to Anıl Çörekçioğlu Quora answer

  • Related