小编典典

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

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

当我在上面的输入文件中搜索并将“ ram”替换为“ abcd”时,它起了一种魅力。但是,反之亦然,即用“ 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

阅读 1081

收藏
2020-02-12

共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='')
2020-02-12
小编典典

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

除非您要处理的海量文件太大而无法一次加载到内存中,否则您担心如果在将数据写入文件的第二步期间该过程被中断,则可能会丢失数据。

2020-02-12