pythonif-statementstring-matching

How to open a file in python, read the comments ("#"), find a word after the comments and select the word after it?


I have a function that loops through a file that Looks like this:

"#" XDI/1.0 XDAC/1.4 Athena/0.9.25

"#" Column.4:                      pre_edge

Content

That is to say that after the "#" there is a comment. My function aims to read each line and if it starts with a specific word, select what is after the ":"

For example if I had These two lines. I would like to read through them and if the line starts with "#" and contains the word "Column.4" the word "pre_edge" should be stored.

An example of my current approach follows:

with open(file, "r") as f:
        for line in f:
            if line.startswith ('#'):
                word = line.split(" Column.4:")[1]
            else:
                print("n")

I think my Trouble is specifically after finding a line that starts with "#" how can I parse/search through it? and save its Content if it contains the desidered word.


Solution

  • In case that # comment contain str Column.4: as stated above, you could parse it this way.

    with open(filepath) as f:
        for line in f:
            if line.startswith('#'):
                # Here you proceed comment lines
                if 'Column.4' in line:
                    first, remainder = line.split('Column.4: ')
                    # Remainder contains everything after '# Column.4: '
                    # So if you want to get first word ->
                    word = remainder.split()[0]
            else:
                # Here you can proceed lines that are not comments
                pass
    

    Note

    Also it is a good practice to use for line in f: statement instead of f.readlines() (as mentioned in other answers), because this way you don't load all lines into memory, but proceed them one by one.