在桌面上的我的数据文件里的p文件里有t1.csv,t2.csv,t3.csv。如何用python给t1.csv,t2csv,t3csv在第一行添加data,name,age
时间: 2024-03-01 11:26:41 浏览: 70
Python给文件添加时间、姓名等后缀
可以使用Python的csv模块来读写csv文件。具体步骤如下:
1. 导入csv模块
```python
import csv
```
2. 打开csv文件并读取数据
```python
with open('t1.csv', 'r') as f:
reader = csv.reader(f)
data = list(reader)
```
3. 在数据的第一行添加要插入的内容
```python
data.insert(0, ['data', 'name', 'age'])
```
4. 写入修改后的数据到csv文件中
```python
with open('t1.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
```
完整代码:
```python
import csv
# 处理t1.csv
with open('t1.csv', 'r') as f:
reader = csv.reader(f)
data = list(reader)
data.insert(0, ['data', 'name', 'age'])
with open('t1.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
# 处理t2.csv
with open('t2.csv', 'r') as f:
reader = csv.reader(f)
data = list(reader)
data.insert(0, ['data', 'name', 'age'])
with open('t2.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
# 处理t3.csv
with open('t3.csv', 'r') as f:
reader = csv.reader(f)
data = list(reader)
data.insert(0, ['data', 'name', 'age'])
with open('t3.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
```
上述代码可以批量处理t1.csv、t2.csv、t3.csv文件,将每个文件的第一行添加data、name、age三列。
阅读全文