相关疑难解决方法(0)

如何使用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 …
Run Code Online (Sandbox Code Playgroud)

python string replace file python-3.x

179
推荐指数
8
解决办法
52万
查看次数

标签 统计

file ×1

python ×1

python-3.x ×1

replace ×1

string ×1