Wie suche und ersetze ich Text in einer Datei in Python?
In diesem Artikel erfahren wir, wie wir Text in einer Datei mit Python ersetzen können.
Methode 1: Suchen und Ersetzen von Text ohne Verwendung eines externen Moduls
Mal sehen, wie wir Text in einer Textdatei suchen und ersetzen können. Zuerst erstellen wir eine Textdatei, in der wir Text suchen und ersetzen möchten. Lassen Sie diese Datei SampleFile.txt mit dem folgenden Inhalt sein:
Um Text in einer Datei zu ersetzen, öffnen wir die Datei schreibgeschützt mit der Funktion open(). Dann lesen und ersetzen wir den Inhalt in der Textdatei mit den Funktionen read() und replace().
Syntax: open(file, mode='r')
Parameter:
- file : Speicherort der Datei
- Modus: Modus, in dem Sie die Datei öffnen möchten.
Dann öffnen wir dieselbe Datei im Schreibmodus, um den ersetzten Inhalt zu schreiben.
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")
Ausgabe:
Text replaced
Methode 2: Suchen und Ersetzen von Text mit dem pathlib2-Modul
Mal sehen, wie wir mit dem pathlib2-Modul Text suchen und ersetzen können. Zuerst erstellen wir eine Textdatei, in der wir Text suchen und ersetzen möchten. Lassen Sie diese Datei SampleFile.txt mit dem folgenden Inhalt sein:
Installieren Sie das pathlib2-Modul mit dem folgenden Befehl:
pip install pathlib2
Dieses Modul bietet Klassen, die Dateisystempfade mit einer für verschiedene Betriebssysteme geeigneten Semantik darstellen. Um den Text mit dem pathlib2-Modul zu ersetzen, verwenden wir die Path-Methode des pathlib2-Moduls.
Syntax: Pfad(Datei)
Parameter:
- Datei: Speicherort der Datei, die Sie öffnen möchten
Im folgenden Code ersetzen wir „dummy“ durch „replaced“ in unserer Textdatei. mit dem Modul pathlib2.
Code:
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))
Ausgabe:
Text replaced
Methode 3: Suchen und Ersetzen von Text mit dem Regex-Modul
Mal sehen, wie wir Text mit dem Regex-Modul suchen und ersetzen können. Wir werden die Methode re.sub( ) verwenden, um den Text zu ersetzen.
Syntax: re.sub(Muster, Repl, String, Anzahl=0, Flags=0)
Parameter:
- repl : Text, den Sie hinzufügen möchten
- string : Text, den Sie ersetzen möchten
Code:
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))
Ausgabe:
Text replaced
Methode 4: Verwenden von fileinput
Sehen wir uns an, wie wir mit dem fileinput-Modul Text suchen und ersetzen können. Dazu verwenden wir die Methode FileInput(), um die Daten der Datei zu durchlaufen und den Text zu ersetzen.
Syntax: FileInput(files=None, inplace=False, backup=”, *, mode='r')
Parameter:
- files : Speicherort der Textdatei
- Modus: Modus, in dem Sie die Datei öffnen möchten
- inplace : Wenn der Wert True ist, wird die Datei in eine Sicherungsdatei verschoben und
- Die Standardausgabe wird an die Eingabedatei geleitet
- backup : Erweiterung für die Sicherungsdatei
Code:
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))
Ausgabe:
Text replaced