Clear file contents if file is opened as "a" append

Question:

Given :

with open("some file path", mode="a", encoding='utf-8') as envConfig_file:
     pass

Is there a way to clear the whole file without opening the file again as "w"?

Asked By: gabriel munteanu

||

Answers:

You can use the seek and truncate methods.

As a side note, for reading and then rewriting, the more usual mode would be r+

with open("some file path", mode="r+", encoding='utf-8') as envConfig_file:
    ... # read the file
    envConfig_file.seek(0)
    envConfig_file.truncate()
    ... # write new contents
Answered By: Jiří Baum
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.