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

后端 未结 3 1940
一个人的身影
一个人的身影 2021-01-19 12:19

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 o         


        
相关标签:
3条回答
  • 2021-01-19 12:37
    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    
    
    0 讨论(0)
  • 2021-01-19 12:47

    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)
    
    0 讨论(0)
  • 2021-01-19 12:58

    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

    0 讨论(0)
提交回复
热议问题