Fergal.P
Fergal.P

Reputation: 107

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

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.

Upvotes: 5

Views: 47889

Answers (3)

Raja Govindan
Raja Govindan

Reputation: 195

Read every line in the file (for loop)
Select lines that contains X:
Slice the line with index 0: with starting char's/string as X: = ln[0:]
Print lines that begins with X:

for ln in input_file:
    if  ln.startswith('X:'):
        X_ln = ln[0:]
        print (X_ln)

Upvotes: 1

Jay
Jay

Reputation: 59

for line in f:
        search = line.split
        if search[0] = "X":
            storagearray.extend(search)

That should give you an array of all the lines you want, but they'll be split into separate words. Also, you'll need to have defined storagearray before we call it in the above block of code. It's an inelegant solution, as I'm a learner myself, but it should do the job!

edit: If you want to output the lines, simply use python's inbuilt print function:

str(storagearray)    
print storagearray    

Upvotes: 0

gkusner
gkusner

Reputation: 1244

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

Upvotes: 15

Related Questions