mcadams
mcadams

Reputation: 21

Empty the file contents or truncate file in python

I am opening a file called test.txt with the file object say file1. Without closing the previously opened file, I am opening same file test.txt with file object say file2 and trying to empty the file contents with file.truncate(0).

I can see my file contents are not getting deleted. Is there any way I can fix this?

import os
def _write(_file):
        _file.write("Hello World")

file1=open("test.txt",'a')

_write(file1)

file2=open("test.txt",'a')
file2.truncate(0)

I want delete the file contents without using same file object file1 because the the code which deletes the file contents is in different file.

Upvotes: 0

Views: 442

Answers (2)

rafettopcu
rafettopcu

Reputation: 41

You can use with in order to close file after the process done.

with open("test.txt",'a') as file1:
    _write(file1)

with open("test.txt",'a') as file2:
    file2.truncate(0)

Upvotes: 1

josoler
josoler

Reputation: 1423

One way to empty a file is opening it in writing mode. You can close it right after:

open('test.txt', 'w').close()

Upvotes: 0

Related Questions