Search code examples
pythonreplaceeol

In Python: replace in a multiline file from a given point to the end of lines


new in Python (and almost in programming).

I have a file with some lines, for example

...
dr=%%dr
mkl=%%mkl
...

I want to replace the %%dr and %%mkl with zeroes in order to have, for example

...
dr=0
mkl=0
...

BUT I don't know in advance which names I will have (whether dr, mkl or some other strange name), so I'd like to write a code that finds any "%%" and replace it and the rest of the line with a 0.


Solution

  • I believe you are looking for something similar to this using regex.

    Note in the regex "%%.*$", matches everything from %% to end of line. Per your requirement, as shown in this example, multiple instances of the your pattern won't be considered as the first pattern would be replaced till the eol.

    >>> st="""new in Python (and almost in programming).
    
    I have a file with some lines, for example
    
    ...
    
    dr=%%dr
    
    mkl=%%mkl
    
    ...
    
    I want to replace the %%dr and %%mkl with zeroes in order to have, for example
    
    ..."""
    >>> lines = (re.sub("%%.*$","0",line) for line in st.splitlines())
    >>> print '\n'.join(lines)
    new in Python (and almost in programming).
    
    I have a file with some lines, for example
    
    ...
    
    dr=0
    
    mkl=0
    
    ...
    
    I want to replace the 0
    
    ...
    >>>