Python replace symbol in 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.

Читайте также:  Php date and time timezone

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 Replace String in File

Oftentimes, the data stored within files needs to be changed or replaced with some different data. This can be done in Python by using simple handling operations, which include opening, reading, writing, and closing the file using the built-in methods. This post will act as a guide on how to replace or change a string in the same file or in different files.

How to Replace String in Different Files?

If the user wants to read a file’s content, replace a certain string or a substring in the data and then store the new content in a separate file, then that is possible with the replace() method along with the open(), read() and write() methods. To demonstrate this, start by opening up the first file using the following line:

After that, read the content of the file by using the read() method:

The content of the file that we are reading is:

The goal is to replace “Hello World!” with “Hello Python!”, and to do this use the following replace() method:

Now the “data” variable contains the modified strings, all you need to do is open the output file (write mode) and write the new data inside it using the following lines:

After this code has been executed, open up the output file and observe the content:

As you can see in the output, a certain string has been replaced in the file’s content.

How to Replace String in the Same Files?

The same procedure that you have followed in the previous section can be used to change or replace a string’s content. To do this, use the following code:

readFile = open ( «readMe.txt» , «r» )

data = data.replace ( «World!» , «Python!» )

writeFile = open ( «readMe.txt» , «w» )
writeFile.write ( data )

In this code, the same file is opened first through the read mode, and then through the write mode, and when this code is executed, it replaces the content of the file:

The output verifies that the substring has been replaced in the file’s string

How to Replace String in File Using Path Package?

The Path package from the pathlib library is used to open a stream to a file with both read and write modes. This allows the user to simultaneously read the data from a file, replace its content and then write it back to the file. For this, the path module contains the function read_text() and write_text() respectively.

To perfect this replacement of string in a file’s string, take the following content of the file “readMe.txt”:

To replace the substring “some” with “replaced” use the following lines of code:

file.write_text ( file.read_text ( ) .replace ( «some» , «replaced» ) )

When this above code is executed, it produces the following changes in the file’s content:

It can be observed that the content of the file has been replaced according to the requirements.

Conclusion

To replace a string in a file the user can have two approaches, one is to change the content and place it in a different file and one is to place it in the same file. Both of these approaches can be performed with the help of the built-in open(), read(), replace(), and write() methods. Alternatively, to replace the content in the same file, the user can also utilize the Path module from the pathlib library.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor’s degree in computer science.

Источник

Replace String in File Using Python

Replace String in File Using Python

  1. Use the replace() Function When Input and Output Files Are Different
  2. Use the replace() Function When Only One File Is Used for Input and Output

File handling is an essential aspect of any web application. Python, similar to other programming languages, supports file handling. It allows the programmers to deal with files and essentially perform some basic operations like reading, writing, and some other file handling options to operate on files.

The open() function can be used to open a file in the Python program. The file can be opened in either text or binary mode which is decided by the user. The open() function has several modes, all of which provide different accessibility options for the file to be opened in.

The term string in Python can be described as a cluster of Unicode characters enclosed within single or double quotes. Strings can be contained inside the text files that are to be opened in the Python code.

This tutorial will discuss different methods to replace a string in a file in Python.

Use the replace() Function When Input and Output Files Are Different

The replace() method in Python is utilized to search for a sub-string and replace it with another sub-string.

The replace() function has three parameters, namely oldvalue , newvalue , and count . Both oldvalue and newvalue are required values, and providing the function with the count parameter is optional.

The following code uses the replace() function to replace a string in Python when input and output files are different.

# the input file fin = open("f1.txt", "rt") # the output file which stores result fout = open("f2.txt", "wt") # iteration for each line in the input file for line in fin:  # replacing the string and write to output file  fout.write(line.replace('gode', 'God')) #closing the input and output files fin.close() fout.close() 

In the output of the above code, the string gode in the file will be replaced by the word God .

In the above code, we simultaneously work on two different files, f1.txt and f2.txt . f1.txt is opened in the read text rt mode and is referenced to fin . f2.txt is opened in the write text wt mode and is referenced to fout . Then the for loop is iterated, and for every occurrence of the string gode in the file, it gets replaced by the word God . Both the files are then closed after the necessary operations with the help of the close() function.

Use the replace() Function When Only One File Is Used for Input and Output

In this method, the same file is used as both input and output.

We use the with statement here along with the replace() function. The with context manager has a fundamental function: making the program shorter and much more readable.

When we use the with statement with File handling, the file that we opened in the Python code doesn’t need to be manually closed; it automatically closes after the with block terminates.

The following code uses the replace() function to replace a string in Python when the input and output file is the same.

with open("file1.txt", "rt") as file:  x = file.read()  with open("file1.txt", "wt") as file:  x = x.replace("gode","God")  fin.write(x) 

The following code takes file1 as both the input and output file. Firstly, the file is opened in the read text rt mode, and the contents of the file are read and stored in a variable. Then, the file is closed and opened again, but in the write text mode wt this time. The string is replaced, and the data is written in this mode, and then the file is closed.

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article — Python File

Related Article — Python String

Copyright © 2023. All right reserved

Источник

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