Read and replace python

Search and Replace a Text in a File in Python

In this article, we will learn to search and replace a text of a file in Python. We will use some built-in functions and some custom codes as well. We will replace text, or strings within a file using mentioned ways.

Python provides multiple built-in functions to perform file handling operations. Instead of creating a new modified file, we will search a text from a file and replace it with some other text in the same file. This modifies the file with new data. This will replace all the matching texts within a file and decreases the overhead of changing each word. Let us discuss some of the mentioned ways to search and replace text in a file in Python.

Sample Text File

We will use the below review.text file to modify the contents.

In the movie Ghost the joke is built on a rock-solid boundation the movie would still work played perfectly straight The notion of a ghost-extermination squad taking on the paramal hordes makes a compelling setup for a big-budget adventure of any stripe Indeed, the film as it stands frequently allows time to pass without a gag But then comes the punch line: the characters are funny And because we’ve been hooked by the story, the humor the characters provide is all the richer.

Example: Use replace() to Replace a Text within a File

The below example uses replace() function to modify a string within a file. We use the review.txt file to modify the contents. It searches for the string by using for loop and replaces the old string with a new string.

Читайте также:  Unchecked assignment java util list to java util list java lang string

open(file,’r’) — It opens the review.txt file for reading the contents of the file.

strip() — While iterating over the contents of the file, strip() function strips the end-line break.

replace(old,new) — It takes an old string and a new string to replace its arguments.

file.close() — After concatenating the new string and adding an end-line break, it closes the file.

open(file,’w’) — It opens the file for writing and overwrites the old file content with new content.

reading_file = open("review.txt", "r") new_file_content = "" for line in reading_file: stripped_line = line.strip() new_line = stripped_line.replace("Ghost", "Ghostbusters") new_file_content += new_line +"\n" reading_file.close() writing_file = open("review.txt", "w") writing_file.write(new_file_content) writing_file.close()

Output:

Example: Replace a Text using Regex Module

An alternative method to the above-mentioned methods is to use Python’s regex module. The below example imports regex module. It creates a function and passed a file, an old string, and a new string as arguments. Inside the function, we open the file in both read and write mode and read the contents of the file.

compile() — It is used to compile a regular expression pattern and convert it into a regular expression object which can then be used for matching.

escape() It is used to escape special characters in a pattern.

sub() It is used to replace a pattern with a string.

#importing the regex module import re #defining the replace method def replace(filePath, text, subs, flags=0): with open(file_path, "r+") as file: #read the file contents file_contents = file.read() text_pattern = re.compile(re.escape(text), flags) file_contents = text_pattern.sub(subs, file_contents) file.seek(0) file.truncate() file.write(file_contents) file_path="review.txt" text="boundation" subs="foundation" #calling the replace method replace(file_path, text, subs)

Output:

FileInput in Python

FileInput is a useful feature of Python for performing various file-related operations. For using FileInput, fileinput module is imported. It is great for throwaway scripts. It is also used to replace the contents within a file. It performs searching, editing, and replacing in a text file. It does not create any new files or overheads.

Syntax-

FileInput(filename, inplace=True, backup='.bak')

Parameters-

backup — The backup is an extension for the backup file created before editing.

Example: Search and Replace a Text using FileInput and replace() Function

The below function replaces a text using replace() function.

import fileinput filename = "review.txt" with fileinput.FileInput(filename, inplace = True, backup ='.bak') as f: for line in f: if("paramal" in line): print(line.replace("paramal","paranormal"), end ='') else: print(line, end ='') 

Output:

Conclusion

In this article, we learned to search and replace a text, or a string in a file by using several built-in functions such as replace() , regex and FileInput module. We used some custom codes as well. We saw outputs too to differentiate between the examples. Therefore, to search and replace a string in Python user can load the entire file and then replaces the contents in the same file instead of creating a new file and then overwrite the file.

Источник

Python – How to Replace String in File?

To replace a string in File using Python, follow these steps:

  1. Open input file in read mode and handle it in text mode.
  2. Open output file in write mode and handle it in text mode.
  3. For each line read from input file, replace the string and write to output file.
  4. Close both input and output files.

Examples

1. Replace a string in File

Consider that we have a text file with some spelling mistakes. And we have found that the string python is mis-spelled as pyton in the file.

In the following example, we will replace the string pyton with python in data.txt file, and write the result to out.txt.

Python Program

#input file fin = open("data.txt", "rt") #output file to write the result to fout = open("out.txt", "wt") #for each line in the input file for line in fin: #read replace the string and write to output file fout.write(line.replace('pyton', 'python')) #close input and output files fin.close() fout.close()
  1. Open data.txt in read text rt mode and get the reference to fin.
  2. Open out.txt in write text wt mode and get the reference to fout.
  3. for line in fin :for each line in fin i.e., data.txt, line.replace(): replaces string pyton with python and fout.write: writes to out.txt.
  4. fin.close(): closes the file referenced by fin, fout.close(): closes the file referenced by fout.
Welcome to www.pytonexamples.org. Here, you will find pyton programs for all general use cases.

Output File

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

The string pyton in the file is replaced with the string python.

2. Replace string and update the original file

In the following example, we will replace the string pyton with python in data.txt file, and overwrite the data.txt file with the replaced text.

Python Prgoram

#read input file fin = open("data.txt", "rt") #read file contents to string data = fin.read() #replace all occurrences of the required string data = data.replace('pyton', 'python') #close the input file fin.close() #open the input file in write mode fin = open("data.txt", "wt") #overrite the input file with the resulting data fin.write(data) #close the file fin.close() 
  1. Open file data.txt in read text mode rt.
  2. fin.read() reads whole text in data.txt to the variable data.
  3. data.replace() replaces all the occurrences of pyton with python in the whole text.
  4. fin.close() closes the input file data.txt.
  5. In the last three lines, we are opening data.txt in write text wt mode and writing the data to data.txt in replace mode. Finally closing the file data.txt.
Welcome to www.pytonexamples.org. Here, you will find pyton programs for all general use cases.

The same input file after program execution.

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

Summary

In this tutorial of Python Examples, we learned to replace a string with other in file, with help of well detailed examples.

Источник

Как заменить строку в файле в Python?

В следующем примере мы заменим строку в файле data.txt и запишем результат в out.txt.

#input file fin = open("data.txt", "rt") #output file to write the result to fout = open("out.txt", "wt") #for each line in the input file for line in fin: #read replace the string and write to output file fout.write(line.replace('pyton', 'python')) #close input and output files fin.close() fout.close()
  1. Открыли data.txt в режиме чтения текста rt и получили ссылку на fin.
  2. Открыли out.txt в режиме записи текста wt и получили ссылку на fout.
  3. for line in fin: для каждой строки в fin, т.е. data.txt, line.replace() заменяет строковый pyton на python и fout.write и записывает в out.txt.
  4. fin.close(): закрывает файл, на который ссылается fin, fout.close() закрывает файл, на который ссылается fout.
Welcome to www.tonais.ru. Here, you will find pyton programs for all general use cases.
Welcome to www.tonais.ru. Here, you will find python programs for all general use cases.

Строка pyton в файле заменяется строкой python.

Пример 2: замена в том же файле

В следующем примере мы заменим строку в файле data.txt и перезапишем файл data.txt с замененным текстом.

#read input file fin = open("data.txt", "rt") #read file contents to string data = fin.read() #replace all occurrences of the required string data = data.replace('pyton', 'python') #close the input file fin.close() #open the input file in write mode fin = open("data.txt", "wt") #overrite the input file with the resulting data fin.write(data) #close the file fin.close()
  1. Открыли файл data.txt в режиме чтения текста rt.
  2. fin.read() считал весь текст из data.txt в переменные data.
  3. data.replace() заменил все вхождения во всем тексте.
  4. fin.close() закрыл входной файл data.txt.
  5. В последних трех строках мы открыли data.txt в режиме записи текста wt и записали данные в data.txt в режиме замены. Наконец закрыли файл data.txt.
Welcome to www.tonais.ru. Here, you will find pyton programs for all general use cases.

Тот же входной файл после выполнения программы.

Welcome to www.tonais.ru. Here, you will find python programs for all general use cases.

В этом руководстве в Python мы научились заменять строку на другую в файле с помощью подробных примеров.

Источник

Оцените статью