读取csv文件,写出python代码
时间: 2023-10-04 07:14:12 浏览: 76
以下是读取CSV文件的Python代码示例:
```python
import csv
with open('example.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
print(', '.join(row))
```
以上代码中,我们使用了Python内置的csv模块来读取CSV文件。`open()`函数用于打开CSV文件,`csv.reader()`函数用于读取CSV文件中的每一行数据。我们可以使用`delimiter`参数来指定CSV文件中的分隔符(默认为逗号),`quotechar`参数用于指定引号字符(默认为双引号)。
以下是写入CSV文件的Python代码示例:
```python
import csv
data = [['Name', 'Age', 'Gender'], ['Alice', '25', 'Female'], ['Bob', '32', 'Male'], ['Charlie', '18', 'Male']]
with open('example.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in data:
writer.writerow(row)
```
以上代码中,我们使用了Python内置的csv模块来写入CSV文件。我们使用`csv.writer()`函数来创建一个CSV写入器,使用`delimiter`参数来指定CSV文件中的分隔符(默认为逗号),`quotechar`参数用于指定引号字符(默认为双引号),`quoting`参数用于指定引用方式(默认为`csv.QUOTE_MINIMAL`)。我们可以使用`writerow()`方法来写入CSV文件中的每一行数据。
阅读全文
相关推荐


















