我一定是错过了什么,但我不明白。我有一个csv,它有1200个字段。我只对30感兴趣。你怎么能这样做?我可以读/写整个shebang,这没关系,但我真的很想写出30.我有一个字段列表,我有点乱砍标题。
我如何在下面翻译才能使用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)
答案 0 :(得分:16)
以下是使用DictWriter
仅写出您关注的字段的示例。我会把移植工作留给你:
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)
a,b,c,d,e,f,g,h
1,2,3,4,5,6,7,8
2,3,4,5,6,7,8,9
a,b,d,g
1,2,4,7
2,3,5,8