将如下数据写入到csv文件中
- data.txt
id,name,salary,start_date,dept
1,Rick,623.3,2012-01-01,IT
2,Dan,515.2,2013-09-23,Operations
3,Tusar,611,2014-11-15,IT
4,Ryan,729,2014-05-11,HR
5,Gary,843.25,2015-03-27,Finance
6,Rasmi,578,2013-05-21,IT
7,Pranab,632.8,2013-07-30,Operations
8,Guru,722.5,2014-06-17,Finance
- test.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 导入CSV安装包
import csv
# 写入CSV文件
def getData(srcPath, dstPath):
# 1. 读取数据
data = []
with open(srcPath,'r') as f:
for line in f:
data.append(list(line.strip().split(',')))
# 2. 创建文件对象
f = open(dstPath,'w',encoding='utf-8',newline='')
# 3. 基于文件对象构建 csv写入对象
csv_writer = csv.writer(f)
# 4. 写入csv文件内容
csv_writer.writerows(data)
# 5. 关闭文件
f.close()
return data
# 获取特定行
def getDataFromRow(rol):
return data[rol]
# 获取特定列
def getDataFromCol(col):
return list(zip(*data))[col]
# 主函数
if __name__ == '__main__':
# 起止索引2-6
startIndex = 2
endIndex = 6
# 源数据文件
srcPath = 'data.txt'
# 目标csv文件
dstPath = 'test.csv'
# 写入文件
data = getData(srcPath, dstPath)
# 输出2-6行的对应数据
for i in range(startIndex, endIndex+1):
name = data[i][1]
salary = data[i][2]
print('name: %s, salary: %s' % (name, salary))
执行结果
输出的csv文件