Python中清空文件內容的方法有兩種:
with open("file.txt", "w") as file: file.truncate()
with open("file.txt", "w") as file: file.write("")
無論是使用truncate()方法還是write()方法清空文件內容,都需要以寫入模式(“w”)打開文件。