How can you write code in Python to clear the contents of a file?
To clear the contents of a file, you can use the following code:
filename = "example.txt" # 替换为你要清空内容的文件名
with open(filename, 'w') as file:
file.truncate(0)
The above code uses the open function to open a file, specifying ‘w’ as the parameter to open it in write mode. It then uses the truncate(0) method to clear the file’s content and set the file size to 0. Make sure you have permission to write to the file.