1)代码在末尾添加替换文本,原始位置的文本不变.
你不能替换文件的正文,因为你用信号打开它.这样它就会附加到文件的末尾.
file = open('example.php','rb+')
但这仅在您想要附加到文档末尾时才有效.
要绕过此操作,您可以使用seek()导航到特定行并替换它.或者创建2个文件:input_file和output_file.
2)此外,它不仅仅是替换的文本,而是打印出整行.
这是因为你正在使用:
file.write( line.replace('Original', 'Replacement'))
免费代码:
我已经分为2个文件,一个输入文件和一个输出文件.
首先,它将打开ifile并将所有行保存在名为lines的列表中.
其次,它会读取所有这些行,如果存在’原始’,它将替换它.
更换后,它将保存到更换.
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()未编辑的文件: