在Python中替换文件中的文本 [英] In place replacement of text in a file in Python

查看:215
本文介绍了在Python中替换文件中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑后,我正在使用以下代码通过FTP将文件上传到服务器上

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)代码在末尾添加了替换的文本,原始位置的文本未更改.

您无法替换文件正文,因为您正在使用+信号打开它.这样,它将附加到文件末尾.

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.

file = open('example.php','rb+')

但这仅在您要追加到文档末尾时有效.

But this only works if you want to append to the end of the document.

绕过,您可以使用 seek() 导航至特定线并更换它.或创建2个文件:input_fileoutput_file.

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

这是因为您正在使用:

file.write( line.replace('Original', 'Replacement'))


免费代码:

我已经分为两个文件,一个输入文件和一个输出文件.

I've segregated into 2 files, an inputfile and an outputfile.

首先,它将打开ifile并将所有行保存在名为lines的列表中.

First it'll open the ifile and save all lines in a list called lines.

其次,它将读取所有这些行,并且如果存在'Original',它将对其进行replace.

Second, it'll read all these lines, and if 'Original' is present, it'll 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() 未经编辑的文件,其中包含:

Then if you want to, you may os.remove() the non-edited file with:

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

这篇关于在Python中替换文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆