在 Python 中替换文件中的文本

San*_*ngh 3 python file python-3.x python-3.5

我使用以下代码在编辑后使用 FTP 在服务器上上传文件:

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()    
Run Code Online (Sandbox Code Playgroud)

有一件事,不是替换原来位置的文本,而是代码在末尾添加替换的文本,并且原始位置的文本不变。

此外,它不仅打印出替换的文本,还打印出整行。谁能告诉我如何解决这两个错误?

dot*_*.Py 5

1)代码在末尾添加了替换的文字,原处的文字不变。

您无法在文件正文中进行替换,因为您正在使用+信号打开它。这样它就会附加到文件的末尾。

file = open('example.php','rb+')
Run Code Online (Sandbox Code Playgroud)

但这仅在您想附加到文档末尾时才有效。

绕过这一点,您可以使用seek()导航到特定行并替换它。或者创建 2 个文件:一个input_file和一个output_file.


2)此外,它不仅打印出替换的文本,还打印出整行。

这是因为您正在使用:

file.write( line.replace('Original', 'Replacement'))
Run Code Online (Sandbox Code Playgroud)

免费代码:

我已经分成 2 个文件,一个输入文件和一个输出文件。

首先,它会打开ifile并将所有行保存在名为lines.

其次,它会读取所有这些行,如果'Original'存在,它会读取replace

替换后,它会保存到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'))
Run Code Online (Sandbox Code Playgroud)

然后,如果您愿意,您可以os.remove()将未编辑的文件与:


更多信息: 教程要点:Python 文件 I/O

  • @SanJeetSingh 在这两种情况下都使用 ifile。首先它会读入行,然后它会打开 example.php 输出,清除它,然后你把这些行写回去,留下一个编辑过的文件,但如果出现任何问题,可能会出现一个垃圾文件。 (2认同)