简体   繁体   English

阅读特定行并使用python忽略其他行

[英]Read Specific line and ignore others using python

I have a text file like this: 我有一个这样的文本文件:

input file
yuorvsdsd
dfdsfsd
?dsfsdfsd
sdfsdfs
?dfd
ds

I am trying to make it so that it only reads the lines start with ? 我正在尝试使其仅读取以?开头的行? . The readlines function reads all lines, so I put a condition on it, but I am not satisfied with it, as it's not showing me the accurate results. readlines函数读取所有行,因此我对其施加了条件,但我对它不满意,因为它没有向我显示准确的结果。 I want output to be: 我希望output为:

?dsfsdfsd
?dfd

Program 程序

fp = open("file.txt")
z = fp.readlines
if z=='?':
    print z
fp.close() 

This is the code which I tried. 这是我尝试过的代码。

I would use something like the following: 我将使用以下内容:

with open("file.txt") as fp:
    for line in fp:
        if line.startswith('?'):
            print line

By using a context manager ( with ... as ) the closing of the file will happen automatically after you are done with it. 通过使用上下文管理器( with ... as ),在完成处理后,文件自动关闭。

列表理解使这一过程变得简单:

filtered = [line for line in fp.readlines() if line.startswith("?")]

I think I'd go with a generator expression: 我想我会使用生成器表达式:

(line for line in open('file.txt') if line.startswith('?'))

A complete program looks like: 一个完整的程序如下所示:

lines = (line for line in open('file.txt') if line.startswith('?'))
print ''.join(lines)

Does this not work? 这行不通吗?

with open("file.txt") as fin:
    for line in fin:
        if not line.startswith('>'):
            print line

Alternatively, could you not just pipe this through grep first? 另外,您是否可以不首先通过grep传递它?

Alternatively, you can use line[0] to get the first character of each line. 另外,您可以使用line[0]获取每行的第一个字符。

with open("file.txt") as fp:
    for line in fp:
        if line[0] == '?':
            print line

This is possible because String in Python can be indexed. 这是可能的,因为Python中的String可以被索引。 Python's String, like C, starts with the index 0 . 像C一样,Python的String以索引0开头。 line[0] will give you a character at index 0, which is the first character. line[0]将为您提供索引0处的字符,这是第一个字符。

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

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