简体   繁体   中英

How to ignore a line when using readlines in python?

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 ignore the specific line.
Is there any command we could use in TXT to ignore a specific line when use readlines?

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('#')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM