Replace Strings in Files With PHP & Python


Read {count} times since 2020

There are softwares already that helps to replace a string in a file. Suppose, if you’re making a program that requires saving some data in to a file. By “adding”, the program is actually replacing a word. Let’s see how it’s done in PHPPython.

This is the file where we are going to replace the word :

thisWord
I got thisWord for making it thatWord
replace thisWord already my friend.

We replace the word “thisWord” to “thatWord” containing in this file.

PHP

<?php
$file = "/home/simsu/Other/projects/Programs/PHP/test.txt";
$contents = file_get_contents($file);
$newContent = str_replace("thisWord", "thatWord", $contents);
file_put_contents($file, $newContent);
?>

I’m not using fopen for this, because to make the code short.

Python

import os
file = "/home/simsu/Other/projects/Programs/PHP/test.txt"
fp = open(file, "r+")
contents = fp.read(os.path.getsize(file))
newContent = contents.replace("thisWord", "thatWord")
fp.seek(0)
fp.truncate()
fp.write(newContent)
fp.close()

We use open for getting the contents of the file as well as to write to it. We truncate the file because otherwise the original content will be repeated again and finally the file connection is closed.

Show Comments