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

后端 未结 3 2044
一个人的身影
一个人的身影 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: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

提交回复
热议问题