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>I suspect the issue is that you have the same file open twice, once as <code>newfile</code> and a second time as <code>a</code>. While it should be truncated when you open it as <code>a</code> and then close it, the writes you made on <code>newfile</code> may still appear if the filesystem had cached them until after the truncated version was written.</p>

<p>I suggest only opening the file once. When you need to truncate it, call the <code>truncate</code> method on it.</p>

<pre><code>if word not in line:
    newfile.truncate()
</code></pre>

<p>If you might write more to the file after truncating, you should probably also <code>seek</code> back to the start position (e.g. <code>newfile.seek(0)</code>). If you're going to be done with the file after truncating it, that step is not needed.</p>

python python-2.7