1) 该代码在末尾添加替换的文本,并且原始位置的文本保持不变。
您无法在文件正文中进行替换,因为您正在使用+
信号。这样它将附加到文件的末尾。
file = open('example.php','rb+')
但这仅在您愿意时才有效append到文档末尾。
To bypass你可以使用这个seek()导航到特定行并替换它。或者创建 2 个文件:一个input_file
and an output_file
.
2) 此外,它不只是打印出替换的文本,而是打印出整行。
这是因为你正在使用:
file.write( line.replace('Original', 'Replacement'))
免费代码:
我分为两个文件,一个输入文件和一个输出文件。
首先它会打开ifile
并将所有行保存在名为的列表中lines
.
其次,它会读取所有这些行,如果'Original'
存在,它将replace
it.
替换后会保存到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'))
那么如果你愿意的话,你可以os.remove()未编辑的文件包含:
更多信息: 教程要点:Python 文件 I/O