从文件中读取以特定字符开头的每一行

Fer*_*l.P 2 python

嗨,我只是学习python,我试图读取以'X:'开头的文件中的每一行。我不想读“ X:”本身,而是接下来的其余部分。

这是到目前为止我得到的:

with open("hnr1.abc","r") as file: f = file.read()
id = []
for line in f:
    if line.startswith("X:"):
        id.append(f.line[2:])
print(id)
Run Code Online (Sandbox Code Playgroud)

它没有任何错误,但不会打印出任何内容。

gku*_*ner 6

尝试这个:

with open("hnr1.abc","r") as fi:
    id = []
    for ln in fi:
        if ln.startswith("X:"):
            id.append(ln[2:])
print(id)
Run Code Online (Sandbox Code Playgroud)

不要使用文件或行之类的名称

请注意,附录仅使用项目名称,而不是文件的一部分

通过将文件预读到内存中,for循环按字符而不是逐行访问数据