Not able to clear file Contents
<p>I have a file which has below data.</p>

<pre><code>edit 48
    set dst 192.168.4.0 255.255.255.0
    set device "Tague-VPN"
    set comment "Yeshtel"
edit 180
    set dst 64.219.107.45 255.255.255.255
    set device "Austin-Backup"
    set comment "images.gsmc.org"
</code></pre>

<p>I want to copy the commands under edit only if Set device is Austin-Backup.</p>

<pre><code>string = 'set device'

word = '"Austin-Backup"'

with open('test.txt') as oldfile, open('script.txt', 'w') as newfile:

    for line in oldfile:
        newfile.write(line)
        newfile.write('\n')
        if string not in line:
            pass
        elif string in line:
            if word not in line:
                a = open('script.txt', 'w')
                a.close()

        else:
            pass
</code></pre>

<p>I am trying to write test file content to new file(script) and if command "set comment "Yeshtel"" is found i want to delete contents in new file. I tried to delete but its not happening. I am new to Python, Can you please tell what is the Prob??</p>

<p>I got to know that reopening the same file in Write mode will clear the contents..</p>

<p>Should be something like this</p>

<pre><code>temp_lines = []
last_line_was_edit = False
found_keyword = False
keyword = "Austin-Backup"
with open('test.txt') as oldfile, open('script.txt', 'w') as newfile:
    for line in oldfile:
        if last_line_was_edit and temp_lines:
            if found_keyword:
                newfile.writelines(temp_lines)
            temp_lines = []

        if line.startswith("edit"):
            last_line_was_edit = True
        else:
            if keyword in line:
                found_keyword = True
            temp_lines.append(line)
</code></pre>

<p>Please note that you should not open the file twice. Just use an temporary variable and write only what have to be written</p>

python python-2.7