Python - How to add a space string (' ') to the end of every line in a text/conf file
Question: I have a config file that i would like to add a space (' ') to the end of
every line in the file

**File example:**

    
    
    #xxx configuration
    IPaddr = 1.1.1.1<add a space here>
    host = a.b.c.d<add a space here>
    usrname = aaa<add a space here>
    dbSID = xxx<add a space here>
    

i already have the number of lines in the file (using len) so i know how much
time to repeat the loop of adding the space string. i also know how to open a
file for reading and writing.

Thank you all.


Answer: You can use [fileinput](https://docs.python.org/2/library/fileinput.html) with
`inplace=True` to update the original file:

    
    
    import fileinput
    import sys
    for line in fileinput.input("in.txt",inplace=True):
        sys.stdout.write("{} \n".format(line.rstrip()))
    

Or use a
[tempfile.NamedTemporaryFile](https://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile)
with [shutil.move](https://docs.python.org/2/library/shutil.html#shutil.move):

    
    
    from tempfile import NamedTemporaryFile
    from shutil import move
    
    with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:   
        for line in f:
           temp.write("{} \n".format(line.rstrip()))
    move(temp.name,"in.txt")
    

