python read line by line and keep indent

Souvik Dutta souvik.viksou at gmail.com
Sat Apr 18 00:42:15 EDT 2020


You can actually read and write in a file simultaneously. Just replace "r"
with "w+" if the file has not been previously made or use "r+" is the file
has already been made.

Souvik flutter dev

On Sat, Apr 18, 2020, 4:45 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.
>
> How to fix this issue.
>
>         reading_file = open("myfile.py", "r")
>         new_file_content = ""
>         for line in reading_file:
>             stripped_line = line.strip()
> #            print (stripped_line)
>             if (stripped_line.find('siteip = ') != -1):
>                 stripped_line = "siteip = \"%s\"" %(siteip)
>             new_line = stripped_line
>             new_file_content += new_line +"\n"
>         reading_file.close()
>         writing_file = open("myfile", "w")
>         writing_file.write(new_file_content)
>         writing_file.close()
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list