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"?
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
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"?
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