300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python怎么建立替换_Python-如何搜索和替换文件中的文本?

python怎么建立替换_Python-如何搜索和替换文件中的文本?

时间:2020-04-03 17:16:15

相关推荐

python怎么建立替换_Python-如何搜索和替换文件中的文本?

如何使用Python 3搜索和替换文件中的文本?

这是我的代码:

import os

import sys

import fileinput

print ("Text to search for:")

textToSearch = input( "> " )

print ("Text to replace it with:")

textToReplace = input( "> " )

print ("File to perform Search-Replace on:")

fileToSearch = input( "> " )

#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):

if textToSearch in line :

print('Match Found')

else:

print('Match Not Found!!')

tempFile.write( line.replace( textToSearch, textToReplace ) )

tempFile.close()

input( '\n\n Press Enter to exit...' )

输入文件:

hi this is abcd hi this is abcd

This is dummy text file.

This is how search and replace works abcd

当我在上面的输入文件中搜索并将“ ram”替换为“ abcd”时,它起了一种魅力。但是,反之亦然,即用“ ram”替换“ abcd”时,一些垃圾字符会保留在末尾。

用“ ram”代替“ abcd”

hi this is ram hi this is ram

This is dummy text file.

This is how search and replace works rambcd

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。