pyhton 查阅csv文件
时间: 2024-09-27 15:01:04 浏览: 44
在Python中,查阅CSV文件通常使用内置的`csv`模块。这个模块提供了一种简单的方式来读取和写入CSV(Comma-Separated Values)数据。以下是一个基本步骤:
1. 导入库:首先需要导入`csv`模块,例如:
```python
import csv
```
2. 打开文件:使用`open()`函数打开CSV文件,记得指定模式`'r'`(只读)或`'w'`(写入),还有文件路径:
```python
with open('file.csv', 'r') as csvfile:
# 或者如果文件编码非UTF-8,可以加上 encoding 参数
with open('file.csv', 'r', encoding='utf-8') as csvfile:
```
3. 读取内容:你可以使用`csv.reader`或`csv.DictReader`(如果你的CSV文件的第一行包含列名)来逐行读取数据:
```python
reader = csv.reader(csvfile)
# 或者
reader = csv.DictReader(csvfile)
for row in reader:
print(row) # 输出每一行作为列表或字典
```
4. 写入数据:如果你想写入数据到CSV文件,可以用`csv.writer`或`csv.DictWriter`:
```python
fields = ['Field1', 'Field2', 'Field3']
writer = csv.DictWriter(csvfile, fieldnames=fields)
# 写入表头
writer.writeheader()
# 写入数据
data_dict = {'Field1': 'Value1', 'Field2': 'Value2', 'Field3': 'Value3'}
writer.writerow(data_dict)
```
阅读全文
相关推荐


















