Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the implementation methods of searching and replacing text in files in Python

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what are the ways to search and replace the text in files in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Method 1: search and replace text without using any external modules

Let's see how to search for and replace text in a text file. First, we create a text file in which we search for and replace text. Set this file to Haiyong.txt, as follows:

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

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

Parameters:

File: location of the file

Mode: mode in which you want to open the file

Then we will open the same file in write mode and write the replacement content.

# create a variable and store the text we want to search for search_text = "resource" # create a variable and store the text we want to add replace_text = "join the group" # use the open () function to open our text file with open in read-only mode 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 for and replace the text data = data.replace (search_text, replace_text) # Open our text file in write-only mode to write the replacement content with open Encoding='UTF-8') as file: # write replacement data in our text file file.write (data) # print text has replaced print ("text has been replaced")

Output:

Text has been replaced

Method 2: search and replace text using the pathlib2 module

Let's see how to search and replace text using the pathlib2 module. First, we create a text file in which we search for and replace text. Set this file to Haiyong2.txt, as follows:

Install the pathlib2 module using the following command:

Pip install pathlib2

This module provides classes that represent file system paths, whose semantics are applicable to different operating systems. To replace the text with the pathlib2 module, we will use the Path method of the pathlib2 module.

Syntax: path (file)

Parameters:

File: the location of the file to open

In the following code, we replace "get more learning materials" in the text file with "ask the group owner to get a physical book". Use the pathlib2 module.

Code:

# Import path from pathlib2 import Path# from pathlib2 module to 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 it in the data variable data = file.read_text () # replace the text data = data.replace (search_text) with the replacement function Replace_text) # write replacement data file.write_text (data) # return "text replaced" string return "text replaced" # create a variable and store the text we want to search search_text = "Python" # create a variable and store the text we want to update replace_text = "Java" # tone Use the replacetext function and print the returned statement print (replacetext (search_text) Replace_text))

Output:

Text has been replaced

Method 3: search and replace text using the regular expression module

Let's see how to search and replace text using the regex module. We will 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 re module import re# to create a function to replace the text def replacetext (search_text,replace_text): # Open the file with open ('SampleFile.txt') in read-write mode 'ringing') as f: # read the file data and store it in the file variable file = f.read () # replace the pattern file = re.sub (search_text, replace_text) with the string in the file data File) # set location to insert data f.seek (0) # write replacement data in the file f.write (file) # truncate the file size f.truncate () # return "text" This has replaced "string return" text has replaced "# create a variable and store the text we want to search 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))

Output:

Text has been replaced

Method 4: use file input

Let's see how to search and replace text using the fileinput module. To do this, we will use the FileInput () method to iterate over the data of the file and replace the text.

Syntax: FileInput (files=None, inplace=False, backup= ", *, mode='r')

Parameters:

Files: location of the text file

Mode: mode in which you want to open the file

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 fileinput import FileInput# from file input module to create a function to replace the text def replacetext (search_text, replace_text): # Open the file with FileInput ("Haiyong4.txt", inplace=True) using FileInput Backup='.bak') as f: # iterate over each with the replace function and use replace_text to change search_text for line in f: print (line.replace (search_text, replace_text) End='') # returns "text replaced" string return "text replaced" # create a variable and store the text we want to search 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))

Output:

Text has been replaced

This is the end of the content of "how to search and replace text in files in Python". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report