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?
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.But this only works if you want to append to the end of the document.
To bypass this you may use
seek()
to navigate to the specific line and replace it. Or create 2 files: aninput_file
and anoutput_file
.2) Also, instead of just the replaced text, it prints out the whole line.
It's because you're using:
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 calledlines
.Second, it'll read all these lines, and if
'Original'
is present, it'llreplace
it.After replacement, it'll save into
ofile
.Then if you want to, you may
os.remove()
the non-edited file with:More Info: Tutorials Point: Python Files I/O
The second error is how the
replace()
method works.It returns the entire input string, with only the specified substring replaced. See example here.
To write to a specific place in the file, you should
seek()
to the right position first.I think this issue has been asked before in several places, I would do a quick search of StackOverflow.
Maybe this would help?
Replacing stuff in a file only works well if original and replacement have the same size (in bytes) then you can do
(In this case
b'Original'
andb'Replacement'
do not have the same size so your file will look funny after this)Edit:
If original and replacement are not the same size, there are different possibilities like adding bytes to fill the hole or moving everything after the line.