写一段python代码来读取csv格式的文件,并给出几个使用示例
时间: 2024-01-14 12:03:03 浏览: 115
python读写csv文件并增加行列的实例代码
好的,以下是一个简单的Python代码示例,用于读取CSV格式的文件:
```python
import csv
# 定义CSV文件路径
csv_file_path = "example.csv"
# 打开CSV文件
with open(csv_file_path, "r") as csv_file:
# 创建CSV文件读取器
csv_reader = csv.reader(csv_file)
# 遍历CSV文件中的每一行数据
for row in csv_reader:
# 处理每一行数据
print(row)
```
这个示例代码中,我们使用了Python内置的CSV模块,通过`csv.reader()`方法来读取CSV文件。然后我们使用`for`循环遍历文件中的每一行数据,并在循环体中处理每一行数据。
下面是几个使用示例:
1. 读取CSV文件并打印每一行数据:
```python
import csv
csv_file_path = "example.csv"
with open(csv_file_path, "r") as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
print(row)
```
2. 读取CSV文件并将每一行数据存储到列表中:
```python
import csv
csv_file_path = "example.csv"
data = []
with open(csv_file_path, "r") as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
data.append(row)
print(data)
```
3. 读取CSV文件并将每一行数据转换成字典:
```python
import csv
csv_file_path = "example.csv"
data = []
with open(csv_file_path, "r") as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
data.append(row)
print(data)
```
4. 将数据写入CSV文件:
```python
import csv
csv_file_path = "example.csv"
data = [
["Name", "Age", "Gender"],
["Tom", 18, "Male"],
["Lucy", 22, "Female"],
["John", 25, "Male"]
]
with open(csv_file_path, "w", newline="") as csv_file:
csv_writer = csv.writer(csv_file)
for row in data:
csv_writer.writerow(row)
print("Data has been written to CSV file successfully!")
```
这个示例代码中,我们使用了`csv.writer()`方法将数据写入CSV文件。需要注意的是,在打开文件时,我们使用了`newline=""`参数来避免出现空白行。
阅读全文