1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import os.path, sys, string
21
22 from pysys.exceptions import *
23
24 -def replace(input, output, dict={}, marker=''):
25 """Read an input file, and write to output tailoring the file to replace set keywords with values.
26
27 The replace method reads in the contents of the input file line by line, checks for matches in
28 each line to the keys in the dictionary dict parameter, and replaces each match with the value
29 of the dictionary for that key, writing the line to the output file. The marker parameter is a
30 character which can be used to denoted keywords in the file to be replaced. For instance, with
31 dict of the form C{{'CATSEAT':'mat', 'DOGSEAT':'hat'}}, marker set to '$', and an input file::
32
33 The cat sat on the $CATSEAT$
34 The dog sat on the $DOGSEAT$
35
36 the ouptut file produced would have the contents::
37
38 The cat sat on the mat
39 The dog sat on the hat
40
41 @param input: The full path to the input file
42 @param output: The full path to the output file with the keywords replaced
43 @param dict: A dictionary of key/value pairs to use in the replacement
44 @param marker: The character used to mark key words to be replaced (may be the empty string
45 if no characters are used)
46 @raises FileNotFoundException: Raised if the input file does not exist
47
48 """
49 if not os.path.exists(input):
50 raise FileNotFoundException, "unable to find file %s" % (os.path.basename(input))
51 else:
52 fi = open(input, 'r')
53 fo = open(output, 'w')
54 for line in fi.readlines():
55 for key in dict.keys():
56 line = line.replace('%s%s%s'%(marker, key, marker), "%s" % (dict[key]))
57 fo.write(line)
58 fi.close()
59 fo.close()
60