In place replacement of text in a file in Python
Question: I am using the following code to upload a file on server using FTP after
editing it:

    
    
    import fileinput
    
    file = open('example.php','rb+')
    
    for line in fileinput.input('example.php'):
        if 'Original' in line :
            file.write( line.replace('Original', 'Replacement'))
    
    file.close()    
    

There is one thing, instead of replacing the text in its original place, the
code adds the replaced text at the end and the text in original place is
unchanged.

Also, instead of just the replaced text, it prints out the whole line. Could
anyone please tell me how to resolve these two errors?


Answer: 1) **The code adds the replaced text at the end and the text in original place
is unchanged.**

You can't replace in the body of the file because you're opening it with the
`+` signal. This way it'll append to the end of the file.

    
    
    file = open('example.php','rb+')
    

But this only works if you want to **append** to the end of the document.

To **bypass** this you may use
[`seek()`](http://stackoverflow.com/questions/11696472/seek-function) to
navigate to the specific line and replace it. Or create 2 files: an
`input_file` and an `output_file`.

* * *

2) **Also, instead of just the replaced text, it prints out the whole line.**

It's because you're using:

    
    
    file.write( line.replace('Original', 'Replacement'))
    

* * *

**Free Code:**

I've segregated into 2 files, an inputfile and an outputfile.

First it'll open the `ifile` and save all lines in a list called `lines`.

Second, it'll read all these lines, and if `'Original'` is present, it'll
`replace` it.

After replacement, it'll save into `ofile`.

    
    
    ifile = 'example.php'
    ofile = 'example_edited.php'
    
    with open(ifile, 'rb') as f:
        lines = f.readlines()
    
    with open(ofile, 'wb') as g:
        for line in lines:
            if 'Original' in line:
                g.write(line.replace('Original', 'Replacement'))
    

Then if you want to, you may
[`os.remove()`](http://docs.python.org/library/os.html#os.remove) the non-
edited file with:

* * *

**More Info:** [Tutorials Point: Python Files
I/O](http://www.tutorialspoint.com/python/python_files_io.htm)

