python 写入csv文件
时间: 2023-09-30 11:05:41 浏览: 58
Python 写入 CSV 文件可以使用内置的 csv 模块,具体步骤如下:
1. 导入 csv 模块
```python
import csv
```
2. 打开文件并创建 csv.writer 对象
```python
with open('file.csv', mode='w', newline='') as file:
writer = csv.writer(file)
```
其中,`mode='w'` 表示以写入模式打开文件,`newline=''` 表示写入时不插入额外的空行。
3. 写入数据
```python
writer.writerow(['Name', 'Age', 'Sex'])
writer.writerow(['Tom', 20, 'Male'])
writer.writerow(['Lily', 18, 'Female'])
```
4. 关闭文件
```python
file.close()
```
完整代码示例:
```python
import csv
with open('file.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'Sex'])
writer.writerow(['Tom', 20, 'Male'])
writer.writerow(['Lily', 18, 'Female'])
file.close()
```