如何使用Python搜索和替换文件中的文本? [英] How to search and replace text in a file using Python?

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

问题描述



这是我的代码:

  import os 
import sys
import fileinput

print(Text to search:)
textToSearch = input (>)

print(Text to replace it with:)
textToReplace = input(>)

print
fileToSearch = input(>)
#fileToSearch ='D:\dummy1.txt'

tempFile = open( fileToSearch,'r +')

在fileinput.input(fileToSearch)中的行:
如果textToSearch在行:
print('Match Found')
其他:
print('Match Not Found !!')
tempFile.write(line.replace(textToSearch,textToReplace))
tempFile.close()


输入('\\\
\\\
按Enter键退出...')

输入文件:


你好,这是abcd这是abcd



这是虚拟文本文件。



这是搜索和替换的工作abcd




当在上述输入文件中搜索并替换'abcd''ram'时,它可以作为一种魅力。但是当我用ram做对比的abcd时,最后会留下一些垃圾字符。



用'ram'替换'abcd' p>


你好,这是ram这是ram



这是虚拟文本文件。 / p>

这是搜索和替换工作的方式ram



解决方案

fileinput 已经支持在线编辑。在这种情况下,它将 stdout 重定向到文件中:

 #! usr / bin / env python3 
import fileinput

with fileinput.FileInput(fileToSearch,inplace = True,backup ='。bak')as file:
for line in file:
print(line.replace(textToSearch,textToReplace),end ='')


How do I search and replace text in a file using Python 3?

Here is my code:

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...' )

Input file:

hi this is abcd hi this is abcd

This is dummy text file.

This is how search and replace works abcd

When I search and replace 'ram' by 'abcd' in above input file, it works as a charm. But when I do vice-verse i.e. 'abcd' by 'ram', some junk characters are left at the end.

Replacing 'abcd' by 'ram'

hi this is ram hi this is ram

This is dummy text file.

This is how search and replace works ram

解决方案

fileinput already supports inplace editing. It redirects stdout to the file in this case:

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(textToSearch, textToReplace), end='')

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

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