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

📅  最后修改于: 2022-05-13 01:54:43.183000             🧑  作者: Mango

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

在本文中,我们将学习如何使用Python替换文件中的文本。

方法一:不使用任何外部模块搜索和替换文本

让我们看看如何在文本文件中搜索和替换文本。首先,我们创建一个文本文件,我们要在其中搜索和替换文本。将此文件设为 SampleFile.txt,内容如下:

要替换文件中的文本,我们将使用 open()函数以只读方式打开文件。然后我们将 t=read 并使用 read() 和 replace() 函数替换文本文件中的内容。

然后我们会以写模式打开同一个文件,写入替换的内容。

Python3
# creating a variable and storing the text
# that we want to search
search_text = "dummy"
  
# creating a variable and storing the text
# that we want to add
replace_text = "replaced"
  
# Opening our text file in read only
# mode using the open() function
with open(r'SampleFile.txt', 'r') as file:
  
    # Reading the content of the file
    # using the read() function and storing
    # them in a new variable
    data = file.read()
  
    # Searching and replacing the text
    # using the replace() function
    data = data.replace(search_text, replace_text)
  
# Opening our text file in write only
# mode to write the replaced content
with open(r'SampleFile.txt', 'w') as file:
  
    # Writing the replaced data in our
    # text file
    file.write(data)
  
# Printing Text replaced
print("Text replaced")


Python3
# Importing Path from pathlib2 module
from pathlib2 import Path
  
# Creating a function to
# replace the text
def replacetext(search_text, replace_text):
  
    # Opening the file using the Path function
    file = Path(r"SampleFile.txt")
  
    # Reading and storing the content of the file in
    # a data variable
    data = file.read_text()
  
    # Replacing the text using the replace function
    data = data.replace(search_text, replace_text)
  
    # Writing the replaced data
    # in the text file
    file.write_text(data)
  
    # Return "Text replaced" string
    return "Text replaced"
  
  
# Creating a variable and storing
# the text that we want to search
search_text = "dummy"
  
# Creating a variable and storing
# the text that we want to update
replace_text = "replaced"
  
# Calling the replacetext function
# and printing the returned statement
print(replacetext(search_text, replace_text))


Python3
# Importing re module
import re
  
# Creating a function to
# replace the text
def replacetext(search_text,replace_text):
  
    # Opening the file in read and write mode
    with open('SampleFile.txt','r+') as f:
  
        # Reading the file data and store
        # it in a file variable
        file = f.read()
          
        # Replacing the pattern with the string
        # in the file data
        file = re.sub(search_text, replace_text, file)
  
        # Setting the position to the top
        # of the page to insert data
        f.seek(0)
          
        # Writing replaced data in the file
        f.write(file)
  
        # Truncating the file size
        f.truncate()
  
    # Return "Text replaced" string
    return "Text replaced"
  
# Creating a variable and storing
# the text that we want to search
search_text = "dummy"
  
#Creating a variable and storing
# the text that we want to update
replace_text = "replaced"
  
# Calling the replacetext function
# and printing the returned statement
print(replacetext(search_text,replace_text))


Python3
# Importing FileInput from fileinput module
from fileinput import FileInput
  
# Creating a function to
# replace the text
def replacetext(search_text, replace_text):
  
    # Opening file using FileInput
    with FileInput("SampleFile.txt", inplace=True,
                   backup='.bak') as f:
  
        # Iterating over every and changing
        # the search_text with replace_text
        # using the replace function
        for line in f:
            print(line.replace(search_text,
                               replace_text), end='')
  
    # Return "Text replaced" string
    return "Text replaced"
  
  
# Creating a variable and storing
# the text that we want to search
search_text = "dummy"
  
# Creating a variable and storing
# the text that we want to update
replace_text = "replaced"
  
# Calling the replacetext function
# and printing the returned statement
print(replacetext(search_text, replace_text))


输出:

Text replaced

方法 2:使用 pathlib2 模块搜索和替换文本

让我们看看如何使用 pathlib2 模块搜索和替换文本。首先,我们创建一个文本文件,我们要在其中搜索和替换文本。将此文件设为 SampleFile.txt,内容如下:

使用以下命令安装 pathlib2 模块:



pip install pathlib2

该模块提供表示文件系统路径的类,其语义适用于不同的操作系统。要使用 pathlib2 模块替换文本,我们将使用 pathlib2 模块的 Path 方法。

在下面的代码中,我们将文本文件中的“dummy”替换为“replaced”。使用 pathlib2 模块。

代码:

蟒蛇3

# Importing Path from pathlib2 module
from pathlib2 import Path
  
# Creating a function to
# replace the text
def replacetext(search_text, replace_text):
  
    # Opening the file using the Path function
    file = Path(r"SampleFile.txt")
  
    # Reading and storing the content of the file in
    # a data variable
    data = file.read_text()
  
    # Replacing the text using the replace function
    data = data.replace(search_text, replace_text)
  
    # Writing the replaced data
    # in the text file
    file.write_text(data)
  
    # Return "Text replaced" string
    return "Text replaced"
  
  
# Creating a variable and storing
# the text that we want to search
search_text = "dummy"
  
# Creating a variable and storing
# the text that we want to update
replace_text = "replaced"
  
# Calling the replacetext function
# and printing the returned statement
print(replacetext(search_text, replace_text))

输出:

Text replaced

方法 3:使用正则表达式模块搜索和替换文本

让我们看看如何使用 regex 模块搜索和替换文本。我们将使用 re.sub() 方法来替换文本。

代码:

蟒蛇3

# Importing re module
import re
  
# Creating a function to
# replace the text
def replacetext(search_text,replace_text):
  
    # Opening the file in read and write mode
    with open('SampleFile.txt','r+') as f:
  
        # Reading the file data and store
        # it in a file variable
        file = f.read()
          
        # Replacing the pattern with the string
        # in the file data
        file = re.sub(search_text, replace_text, file)
  
        # Setting the position to the top
        # of the page to insert data
        f.seek(0)
          
        # Writing replaced data in the file
        f.write(file)
  
        # Truncating the file size
        f.truncate()
  
    # Return "Text replaced" string
    return "Text replaced"
  
# Creating a variable and storing
# the text that we want to search
search_text = "dummy"
  
#Creating a variable and storing
# the text that we want to update
replace_text = "replaced"
  
# Calling the replacetext function
# and printing the returned statement
print(replacetext(search_text,replace_text))

输出:

Text replaced

方法四:使用文件输入

让我们看看如何使用 fileinput 模块搜索和替换文本。为此,我们将使用 FileInput() 方法迭代文件的数据并替换文本。

代码:

蟒蛇3

# Importing FileInput from fileinput module
from fileinput import FileInput
  
# Creating a function to
# replace the text
def replacetext(search_text, replace_text):
  
    # Opening file using FileInput
    with FileInput("SampleFile.txt", inplace=True,
                   backup='.bak') as f:
  
        # Iterating over every and changing
        # the search_text with replace_text
        # using the replace function
        for line in f:
            print(line.replace(search_text,
                               replace_text), end='')
  
    # Return "Text replaced" string
    return "Text replaced"
  
  
# Creating a variable and storing
# the text that we want to search
search_text = "dummy"
  
# Creating a variable and storing
# the text that we want to update
replace_text = "replaced"
  
# Calling the replacetext function
# and printing the returned statement
print(replacetext(search_text, replace_text))

输出:

Text replaced