py对csv文件增删改查的代码
时间: 2023-06-04 18:07:12 浏览: 213
以下是Python中对CSV文件进行增删改查的示例代码:
1. 创建/打开CSV文件
```python
import csv
# 打开或创建一个CSV文件
with open('test.csv', 'w', encoding='utf-8') as f:
writer = csv.writer(f)
# csv文件头部写入数据
writer.writerow(['姓名', '年龄', '性别', '职业'])
```
2. 写入CSV文件数据
```python
import csv
# 打开CSV文件
with open('test.csv', 'a', encoding='utf-8') as f:
writer = csv.writer(f)
# 写入一行数据
writer.writerow(['Tom', '18', '男', '学生'])
writer.writerow(['Lucy', '22', '女', '程序员'])
```
3. 读取CSV文件数据
```python
import csv
# 打开CSV文件
with open('test.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
4. 修改CSV文件数据
```python
import csv
# 打开CSV文件
with open('test.csv', 'r', encoding='utf-8') as f:
rows = []
reader = csv.reader(f)
for row in reader:
if row[0] == 'Tom': # 过滤出要修改的行
row[1] = '20' # 修改第2列
rows.append(row)
# 写入修改后的数据到CSV文件
with open('test.csv', 'w', encoding='utf-8') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
```
5. 删除CSV文件数据
```python
import csv
# 打开CSV文件
with open('test.csv', 'r', encoding='utf-8') as f:
rows = []
reader = csv.reader(f)
for row in reader:
if row[0] != 'Tom': # 过滤出要删除的行
rows.append(row)
# 写入删除后的数据到CSV文件
with open('test.csv', 'w', encoding='utf-8') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
```
以上是对CSV文件进行增删改查的Python示例代码,供参考。