如何搜索和替换文件中的文本?

新手上路,请多包涵

如何使用 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

原文由 Shriram 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 448
2 个回答

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

 #!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

原文由 jfs 发布,翻译遵循 CC BY-SA 4.0 许可协议

正如 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)

除非您要处理一个太大而无法一次性加载到内存中的大文件,或者您担心如果在将数据写入文件的第二步过程中进程中断,可能会丢失数据。

原文由 Jack Aidley 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题