如何使用 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
当我在上面的输入文件中搜索并用“abcd”替换“ram”时,它就像一个魅力。但是当我反之亦然,即用“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
最佳答案
正如 michaelb958 所指出的,您不能用不同长度的数据替换原位,因为这会使其余部分不合适。我不同意其他海报建议您从一个文件读取并写入另一个文件。相反,我会将文件读入内存,修复数据,然后在单独的步骤中将其写入同一个文件。
# Read in the file
with open('file.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('ram', 'abcd')
# Write the file out again
with open('file.txt', 'w') as file:
file.write(filedata)
除非您要处理的文件太大而无法一次性加载到内存中,或者您担心如果在将数据写入第二步的过程中中断可能会丢失数据文件。
https://stackoverflow.com/questions/17140886/