Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read in every line that starts with a certain character from a file

Tags:

python

I am trying to read in every line in a file that starts with an 'X:'. I don't want to read the 'X:' itself just the rest of the line that follows.

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)

It doesn't have any errors but it doesn't print anything out.

like image 617
Fergal.P Avatar asked Dec 11 '22 20:12

Fergal.P


1 Answers

try this:

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

dont use names like file or line

note the append just uses the item name not as part of the file

by pre-reading the file into memory the for loop was accessing the data by character not by line

like image 129
gkusner Avatar answered Dec 13 '22 09:12

gkusner