[英]Python csv.DictReader. Read alter dictionary then output to file
I need to read in a pipe delimited file change some fields and output. It reads in fine and I am able to change the columns.我需要读入 pipe 分隔文件更改一些字段和 output。它读起来很好,我可以更改列。 The writer part writes the header but writerows doesn't write anything. writer 部分写入 header 但 writerows 不写入任何内容。 How can I output the updated contents?我怎样才能output更新内容?
csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)
with open('test.txt') as csvfile
cfile=csv.DictReader(cfile,dialect='pipe')
fieldnames=cfile.fieldnames
for row in cfile:
row['address']=scrubrow(row['address']
with open('c.txt','w') as outfile:
writer=csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')
writer.writeheader()
writer.writerows(cfile)
cfile
is an empty iterator. cfile
是一个空迭代器。 And you discarded all but the last row
, so doing row['address']=scrubrow(row['address']
didn't actually do anything.你丢弃了除最后row
以外的所有内容,所以row['address']=scrubrow(row['address']
实际上没有做任何事情。
The simple way to do this is to create a list and use that list:执行此操作的简单方法是创建一个列表并使用该列表:
csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)
with open('test.txt') as csvfile
reader = csv.DictReader(cfile, dialect='pipe')
fieldnames = cfile.fieldnames
rows = []
for row in reader:
rows.append(scrubrow(row['address']))
with open('c.txt','w') as outfile:
writer = csv.DictWriter(outfile, fieldnames=fieldnames, dialect='pipe')
writer.writeheader()
writer.writerows(rows)
But this will be inefficient because it will require O(N) space.但这将是低效的,因为它需要 O(N) 空间。 Instead, keeping only a single row in memory at a time, you could do:相反,一次只保留 memory 中的一行,您可以这样做:
csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)
with open('test.txt') as csvfile, open('c.txt','w') as outfile:
reader = csv.DictReader(cfile,dialect='pipe')
fieldnames = reader.fieldnames
writer = csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')
writer.writeheader()
for row in reader:
writer.writerow(scrubrow(row['address']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.