with open('filename.txt', 'w') as file:
pass
2. 使用 `open` 函数,指定模式为 `'x'`,如果文件不存在则创建:
with open('filename.txt', 'x') as file:
pass
3. 使用 `os` 模块的 `open` 函数,指定 `os.O_CREAT` 标志:
import os
with os.open('filename.txt', os.O_CREAT) as file:
os.close(file)
4. 使用 `with` 语句和 `open` 函数,文件会被创建但保持为空:
with open('filename.txt', 'w') as file:
pass
5. 使用 `with` 语句和 `open` 函数,文件会被创建但保持为空,并且可以避免显式调用 `close` 方法:
with open('filename.txt', 'w') as file:
pass
以上方法都可以创建一个空文件。使用 `with` 语句的好处是,当 `with` 块内的代码执行完毕后,文件会自动关闭,无需显式调用 `close` 方法。
请选择适合你需求的方法来创建空文件