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

当我在上面的输入文件中搜索并用“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/

相关文章:

python - 将元组转换为列表并返回

python - Django 1.7 抛出 django.core.exceptions.AppR

python - 如何将 python 日期时间转换为具有可读格式日期的字符串?

linux - 每个虚拟主机的error_log?

linux - 如何让 CRON 调用正确的路径

python - 如何访问 Django 模板中的字典元素?

android - 找不到构建工具修订版 23.0.1

linux - 如何找出适合由 shell 脚本解析的 linux 机器的总物理内存 (RAM)?

linux - 检索最后 100 行日志

python - 在进程运行时不断打印子进程输出