Write And Replace Particular Line In File
I want to replace value of key(i.e db_host, addons_path) with $$$$. Input text file contains the following: #Test.txt# addons_path=/bin/root admin_passwd = abctest auto_reload = F
Solution 1:
If you want to do that with Python, you can use the following function:
def replace_in_file(filename, key, new_value):
f = open(filename, "r")
lines = f.readlines()
f.close()
for i, line in enumerate(lines):
if line.split('=')[0].strip(' \n') == key:
lines[i] = key + ' = ' + new_value + '\n'
f = open(filename, "w")
f.write("".join(lines))
f.close()
replace_in_file("file.txt", 'db_host', "7777")
Solution 2:
This is much simpler achieved with UNIX tools.
Nevertheless here's my solution:
bash-4.3$ cat - > test.txt
#Test.txt#
addons_path=/bin/root
admin_passwd = abctest
auto_reload = False
csv_internal_sep = ,
db_host = 90.0.0.1
bash-4.3$ python
Python 2.7.6 (default, Apr 28 2014, 00:50:45)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("test.txt", "r") as f:
... pairs = (line.split("=", 1) for line in f if not line.startswith("#"))
... d = dict([(k.strip(), v.strip()) for (k, v) in pairs])
...
>>> d["db_host"] = "$$$$"
>>> with open("out.txt", "w") as f:
... f.write("\n".join(["{0:s}={1:s}".format(k, v) for k, v in d.items()]))
...
>>>
bash-4.3$ cat out.txt
db_host=$$$$
admin_passwd=abctest
auto_reload=False
csv_internal_sep=,
addons_path=/bin/rootbash-4.3$
- Read the file and parse it's key/value pairs by
=
into adict
(ignoring comments). - Change the
db_host
key in the resulting dictionary. - Write out the dictionary using
=
as key/value separators.
Enjoy :)
Update: As a reuseable set of functions:
def read_config(filename):
with open(filename, "r") as f:
pairs = (line.split("=", 1) for line in f if not line.startswith("#"))
return dict([(k.strip(), v.strip()) for (k, v) in pairs])
def write_config(d, filename):
with open(filename, "w") as f:
f.write("\n".join(["{0:s}={1:s}".format(k, v) for k, v in d.items()]))
Solution 3:
What about something like this ?
def replace_string(s):
s = s.replace('db_host','$$$$')
return s
with open('test.txt','r') as fo:
line = fo.read() # you could use strip() or split() additionally
new_string = replace_string(line)
Solution 4:
use fileinput
module.
import fileinput
for line in fileinput.input('data.txt',backup='.bak',inplace=1):
print line.rstrip().replace('Python','Perl')
#or print line.replace('Python','Perl'),
Post a Comment for "Write And Replace Particular Line In File"