This script use an efficient way to tranform a file's text to something else, with conditions for few lines.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #!/usr/bin/env python
INPUT_FILE = 'input_file.txt'
OUTPUT_FILE = INPUT_FILE + '.out'
def condition():
"""Thid function provides condtion list, and values"""
lst_condition = [('first marker line\n',
'first marker line\n'),
('this line will be changed\n',
'this line is changed like this\n')]
for testcond, value in lst_condition:
yield testcond, value
def parse(cond):
"""parse file and return lines/values"""
check = True
testcond, value = cond.next()
for line in file(INPUT_FILE):
if check:
if line == testcond:
yield value
try:
testcond, value = cond.next()
except StopIteration:
check = False
else:
yield line
else:
yield line
if __name__ == '__main__':
fd = open(OUTPUT_FILE, 'w')
cond = condition()
for line in parse(cond):
fd.write(line)
pass
fd.close()
pass
|
This script will be usefull to change few lines of huge text file.
Tags: text
How is it efficient. Since it is handling every line, I am wondering how is it different from any other approaches. Say, e.g., I could think of this alternative implementation for parse(cond) :
--Hemanth