在Python中,创建文件通常是通过使用 `open()` 函数来完成的。以下是使用 `open()` 函数创建文件的几种模式:
写入模式 (`w`):
如果文件不存在,则创建一个新文件。如果文件存在,则覆盖原有内容。
```python
with open('example.txt', 'w') as file:
file.write('Hello, world!')
追加模式 (`a`):
如果文件不存在,则创建一个新文件。如果文件存在,则在文件末尾追加内容。
```python
with open('example.txt', 'a') as file:
file.write('\nThis is a new line.')
使用 `with` 语句的好处是,当 `with` 块内的代码执行完毕后,文件会自动关闭,无需显式调用 `close()` 方法。
请根据你的需求选择合适的模式来创建文件。