Reputation:
I have a list which has values to search for in a file and a dictionary with the values it should be replaced with,i gave a sample content of the file and the same output,am unsure as to how to search and replace?can anyone provide guidance?
list_to_search =['TRC_BTM', 'TRC_HCI', 'TRC_L2CAP']
dict = {'TRC_BTM': '6', 'TRC_HCI': '6', 'TRC_L2CAP': '6'}
filename ='file.conf'
f = open(filename, 'r')
for value in list_to_search :
print "dummy"
#1.search value in file
#2.replace with dict[value]
f.close()
INPUT:-
#comment1
TRC_BTAPP only.
TRC_BTM=2
TRC_HCI=2
TRC_L2CAP=2
#comment2
OUTPUT:-
#comment1
TRC_BTAPP only.
TRC_BTM=6
TRC_HCI=6
TRC_L2CAP=6
#comment2
...
Upvotes: 2
Views: 146
Reputation: 10951
I've got for you another solution, basically what it does, instead of reading whole content of file into memory, you read line by line and check in each line you read if it has one of elements of list_to_search
, then modify it if so:
list_to_search =['TRC_BTM', 'TRC_HCI', 'TRC_L2CAP']
myDict = {'TRC_BTM': '6', 'TRC_HCI': '6', 'TRC_L2CAP': '6'}
filename ='file.conf'
with open(filename, 'rb+') as f:
while True:
line = f.readline()
if not line: break
for key in list_to_search:
if key in line:
f.seek(-len(line),1)
f.write(key + '=' + myDict[key] + '\n')
f.flush()
EDIT: In response to your comment below:
with open(filename, 'rb+') as f:
while True:
line = f.readline()
if not line: break
if '=2' in line:
f.seek(-len(line),1)
f.write(line.split('=2')[0]+'=6')
f.flush()
Upvotes: 1
Reputation: 8335
If and only if the file contains the strings as your sample input
the following method will work:
Instead of printing, you could write the output into a file if you wish:
My code:
list_to_search =['TRC_BTM', 'TRC_HCI', 'TRC_L2CAP']
dict = {'TRC_BTM': '6', 'TRC_HCI': '6', 'TRC_L2CAP': '6'}
filename ='test.txt'
for a in open(filename):
if any(ext in a for ext in list_to_search):
for value in list_to_search:
if value in a and "=" in a:
print value+"="+dict[value]
else:
print a
Modified Code:
list_to_search =['TRC_BTM', 'TRC_HCI', 'TRC_L2CAP']
dict = {'TRC_BTM': '6', 'TRC_HCI': '6', 'TRC_L2CAP': '6'}
filename ='test.txt'
output_writer=[]
with open(filename, "r") as f:
for a in f:
print a
if any(ext in a for ext in list_to_search):
for value in list_to_search:
if value in a and "=" in a:
output_writer.append(value+"="+dict[value])
#print value+"="+dict[value]
else:
# print a
output_writer.append(a.strip())
output="\n".join(output_writer)
with open(filename, "w") as f:
f.write(output)
Upvotes: 1