Welcome, guest | Sign In | My Account | Store | Cart

This script use an efficient way to tranform a file's text to something else, with conditions for few lines.

Python, 41 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.

1 comment

hemanth sethuram 18 years, 6 months ago  # | flag

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) :

def parse(cond):
    for line in file(INPUT_FILE):
        for test_cond, value in cond:
            changed_line = line.replace(test_cond,value)
            if changed_line != line:
                yield changed_line  #pattern was found
                break #skip to the next line
        if changed_line == line: # pattern was not found
            yield line  # give back the original line

--Hemanth

Created by Baiju M on Mon, 5 Sep 2005 (PSF)
Python recipes (4591)
Baiju M's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks