In place replacement of text in a file in Python

后端 未结 3 1087
借酒劲吻你
借酒劲吻你 2021-01-15 14:51

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 file         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 15:21

    Replacing stuff in a file only works well if original and replacement have the same size (in bytes) then you can do

    with open('example.php','rb+') as f:
        pos=f.tell()
        line=f.readline()
        if b'Original' in line:
            f.seek(pos)
            f.write(line.replace(b'Original',b'Replacement'))
    

    (In this case b'Original' and b'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.

提交回复
热议问题