1. 使用`write()`方法:
```python
with open('example.txt', 'w') as file:
file.write('Hello, world!')
2. 使用`writelines()`方法:
```python
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('example.txt', 'w') as file:
file.writelines(lines)
3. 使用`print()`函数:
```python
print('Hello, world!', file='example.txt')
4. 使用`csv`模块:
```python
import csv
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
with open('example.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
5. 使用`json`模块:
```python
import json
data = {'name': 'John', 'age': 30}
with open('example.json', 'w') as jsonfile:
json.dump(data, jsonfile)
以上示例展示了如何使用不同的方法和模块将数据写入文件。使用`with`语句可以确保文件在使用后自动关闭,无需显式调用`close()`方法。
请告诉我,