python fieldnames_python csv只写某些字段名,不是全部

I must be missing something, but I don't get it. I have a csv, it has 1200 fields. I'm only interested in 30. How do you get that to work? I can read/write the whole shebang, which is ok, but i'd really like to just write out the 30. I have a list of the fieldnames and I'm kinda hacking the header.

How would I translate below to use DictWriter/Reader?

for file in glob.glob( os.path.join(raw_path, 'P12*.csv') ):

fileReader = csv.reader(open(file, 'rb'))

fileLength = len(file)

fileGeom = file[fileLength-7:fileLength-4]

table = TableValues[fileGeom]

filename = file.split(os.sep)[-1]

with open(out_path + filename, "w") as fileout:

for line in fileReader:

writer = csv.writer(fileout, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

if 'ID' in line:

outline = line.insert(0,"geometryTable")

else:

outline = line.insert(0,table) #"%s,%s\n" % (line, table)

writer.writerow(line)

解决方案

Here's an example of using DictWriter to write out only fields you care about. I'll leave the porting work to you:

import csv

headers = ['a','b','d','g']

with open('in.csv','rb') as _in, open('out.csv','wb') as out:

reader = csv.DictReader(_in)

writer = csv.DictWriter(out,headers,extrasaction='ignore')

writer.writeheader()

for line in reader:

writer.writerow(line)

in.csv

a,b,c,d,e,f,g,h

1,2,3,4,5,6,7,8

2,3,4,5,6,7,8,9

Result (out.csv)

a,b,d,g

1,2,4,7

2,3,5,8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值