This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

🌊 author’s home page: Haichong 🌊 Author Profile: πŸ₯‡HDZ core group member, πŸ† full stack quality creator, 🌊 retained the top ten of the weekly list of STATION C fan welfare: fans send four books every week and various small gifts every month (enamel cup, pillow, mouse pad, mugs, etc.)

In this article, I’ll show you how to replace text in files in Python using four methods.

Method one: Search and replace text without using any external modules

Let’s look at how to search and replace text in a text file. First, we create a text file in which we search and replace text. Set this file to haiyong.txt with the following contents:

To replace the text in the file, we will use the open() function to open the file read-only. Then we take t=read and replace the contents of the text file with the read() and replace() functions.

Syntax: open(file, mode=’r’)

Parameters:

File: indicates the location of the file. Mode: indicates the mode to open the file

We then open the same file in write mode and write the replacement.

Create a variable and store the text we want to search for
search_text = "Resources"

Create a variable and store the text we want to add
replace_text = "Into the group of"

# Use the open() function to open our text file in read-only mode
with open(r'Haiyong.txt'.'r',encoding='UTF-8') as file:

	# Use the read() function to read the contents of the file and store them in a new variable
	data = file.read()

	Use the replace() function to search and replace text
	data = data.replace(search_text, replace_text)

# Open our text file in write only mode to write the replacement
with open(r'Haiyong.txt'.'w',encoding='UTF-8') as file:

	Write the replacement data to our text file
	file.write(data)

The printed text has been replaced
print("Text replaced")
Copy the code

Output:

Text replacedCopy the code

Method two: Use the Pathlib2 module to search and replace text

Let’s look at how to search and replace text using the Pathlib2 module. First, we create a text file in which we search and replace text. Set this file to haiyong2.txt with the following contents:

Use the following command to install the pathlib2 module:

pip install pathlib2
Copy the code

This module provides classes that represent file system paths with semantics suitable for different operating systems. To replace the text with the pathlib2 module, we will use the pathlib2 module’s Path method.

Syntax: Path (file)

Parameters:

File: Location of the file to be opened

In the code below, we replace “Get more learning materials” in the text file with “get a physical book from the group owner.” Use the Pathlib2 module.

Code:

Import path from pathlib2 module
from pathlib2 import Path

Create a function to replace the text
def replacetext(search_text, replace_text) :

	Use the Path function to open the file
	file = Path(r"Haiyong2.txt")

	Read the contents of the file and store them in data variables
	data = file.read_text()

	# Replace text with the replace function
	data = data.replace(search_text, replace_text)

	Write the replacement data to the text file
	file.write_text(data)

	# return "Text replaced" string
	return "Text replaced"


Create a variable and store the text we want to search for
search_text = "Python"

Create a variable and store the text we want to update
replace_text = "Java"

# Call the replacetext function and print the returned statement
print(replacetext(search_text, replace_text))
Copy the code

Output:

Text replacedCopy the code

Method 3: Use regular expression modules to search and replace text

Method 3: Search and replace text using the regular expression module Let’s look at how to search and replace text using the Regex module. We’ll use the re.sub() method to replace the text.

Syntax: re.sub(Pattern, repl, string, count=0, flags=0)

Parameters:

Repl: text to add string: text to replace

Code:

Import the re module
import re

Create a function to replace the text
def replacetext(search_text,replace_text) :

	Open the file in read/write mode
	with open('SampleFile.txt'.'r+') as f:

		Read file data and store it in file variables
		file = f.read()
		
		Replace the schema with a string in the file data
		file = re.sub(search_text, replace_text, file)

		Insert data at the top of the page
		f.seek(0)
		
		Write replacement data to the file
		f.write(file)

		Truncate the file size
		f.truncate()

	# return "Text replaced" string
	return "Text replaced"

Create a variable and store the text we want to search for
search_text = "World"

Create a variable and store the text we want to update
replace_text = "Universe"

# Call the replacetext function and print the returned statement
print(replacetext(search_text,replace_text))

Copy the code

Output:

Text replacedCopy the code

Method 4: Use file input

Let’s look at how to search and replace text using the FileInput module. To do this, we’ll use the FileInput() method to iterate over the file’s data and replace the text.

Syntax: FileInput(files=None, inplace=False, backup= “, *, mode=’r’)

Parameters:

Inplace: if the value is True, the file is moved to the backup file and the standard output is directed to the input file. Backup: extension of the backup file

Code:

Import file input from the file input module
from fileinput import FileInput

Create a function to replace the text
def replacetext(search_text, replace_text) :

	Open a file with FileInput
	with FileInput("Haiyong4.txt", inplace=True,
				backup='.bak') as f:

		# Iterate over each using the replace function and change search_text using replace_TEXT
		for line in f:
			print(line.replace(search_text,
							replace_text), end=' ')

	# return "Text replaced" string
	return "Text replaced"


Create a variable and store the text we want to search for
search_text = "unreplaced"

Create a variable and store the text we want to update
replace_text = "replaced"

# Call the replacetext function and print the returned statement
print(replacetext(search_text, replace_text))
Copy the code

Output:

Text replacedCopy the code

I’ve been writing a technical blog for a long time, mostly through Nuggets, and this is my text on how to search and replace files in Python. I like to share technology and happiness through articles. You can visit my blog at juejin.cn/user/204034… For more information. Hope you like it! 😊

πŸ’Œ welcomes your comments and suggestions in the comments section! πŸ’Œ

The nuggets will be drawing 100 nuggets in the comments section after project Digital. see the event article for details