简述Python中如何读取和写入csv文件
时间: 2023-10-09 13:13:52 浏览: 58
在Python中读取和写入CSV文件通常使用CSV模块。CSV模块提供了一种简单的方法来读取和写入CSV文件。下面是读取和写入CSV文件的示例代码:
读取CSV文件:
```python
import csv
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
```
在上面的代码中,我们打开了一个名为example.csv的文件,并使用csv.reader()函数创建了一个CSV读取器。然后,我们使用for循环逐行读取文件,并打印每一行的内容。
写入CSV文件:
```python
import csv
data = [
['Name', 'Age', 'Gender'],
['Alice', 25, 'Female'],
['Bob', 30, 'Male'],
['Charlie', 35, 'Male']
]
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
```
在上面的代码中,我们定义了一个名为data的二维列表,并使用csv.writer()函数创建了一个CSV写入器。然后,我们使用writerows()函数将数据写入到名为example.csv的文件中。注意,我们使用newline=''参数来确保写入的文件具有正确的行结尾符。