python read line by line and keep indent

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Apr 17 20:24:46 EDT 2020


On 18/04/20 11:10 am, hnasr9999 at gmail.com wrote:
> Hi;
> 
> I am reading a Python file and find an specific line, replace a text and then write back to the file.
> 
> When I check back the file, I am getting indent error.

It looks like your script is stripping out all the indentation when
it writes the lines back. Indentation is syntactically significant
in Python, so you need to preserve it.

My suggestions:

1. Don't strip the lines.

2. When you find the 'siteip = ' line, instead of constructing
a whole new line, replace the part after '=' with the new siteip,
so that you keep whatever indentation the line had before.

-- 
Greg


More information about the Python-list mailing list