简体   繁体   English

在 python 中使用 readlines 时如何忽略一行?

[英]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 .现在我们得到 b,其中包含1.txt中的所有行。
But we know that in Python when we don't use a line we could use但我们知道,在 Python 中,当我们不使用线路时,我们可以使用

\# mark

to ignore the specific line.忽略特定行。
Is there any command we could use in TXT to ignore a specific line when use readlines?在使用 readlines 时,我们可以在 TXT 中使用任何命令来忽略特定行吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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