Searching and Replacing the text in a File
Using simple python semantics, we can perform search and replace in a file. Firstly, we will define the file name, along with the words to search and replace. After defining the sets of variables, we will open the file in r+
mode i.e. we can perform read as well as write operations in the file.
We will store the entire file contents using the read function, the contents of file are now stored in the form of a string. We further can set the position of the cursor or the current position in the file using the seek function. The seek function takes in a optional parameter as the position to set for reading/writing of file. Using the truncate function, we can clear all the contents of the file.
Finally, we generate the content by replacing the words i.e. the old word with the new word from the string which we store the contents. After replacing the content in the string, we write the string variable into the file and hence the substitution was performed in the text file.
file_name = 'temp.txt' old_text = 'foo' new_text = 'python' with open(file_name, "r+") as fname: lines = fname.read() fname.seek(0) fname.truncate(0) subs = lines.replace(old_text, new_text) fname.write(subs)
<a class='prev' href='/libsql-query-remote-db'>
<svg width="50px" height="50px" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.5 8.25L9.75 12L13.5 15.75" stroke="var(--prevnext-color-angle)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"> </path>
</svg>
<div class='prevnext-text'>
<p class='prevnext-subtitle'>prev</p>
<p class='prevnext-title'>LibSQL: Query a remote Turso database with cURL</p>
</div>
</a>
<a class='next' href='/git-ssh-multiple-accounts'>
<div class='prevnext-text'>
<p class='prevnext-subtitle'>next</p>
<p class='prevnext-title'>Adding SSH Keys for Multiple Accounts in Git</p>
</div>
<svg width="50px" height="50px" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.5 15.75L14.25 12L10.5 8.25" stroke="var(--prevnext-color-angle)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
</svg>
</a>