Package pysys :: Package utils :: Module filereplace
[hide private]
[frames] | no frames]

Source Code for Module pysys.utils.filereplace

 1  #!/usr/bin/env python 
 2  # PySys System Test Framework, Copyright (C) 2006-2013  M.B.Grieve 
 3   
 4  # This library is free software; you can redistribute it and/or 
 5  # modify it under the terms of the GNU Lesser General Public 
 6  # License as published by the Free Software Foundation; either 
 7  # version 2.1 of the License, or (at your option) any later version. 
 8   
 9  # This library is distributed in the hope that it will be useful, 
10  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
11  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12  # Lesser General Public License for more details. 
13   
14  # You should have received a copy of the GNU Lesser General Public 
15  # License along with this library; if not, write to the Free Software 
16  # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 
17   
18  # Contact: moraygrieve@users.sourceforge.net 
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