简体   繁体   English

Python:有没有办法在调用writerow()之前更新DictWriter的键(列)?

[英]Python: Is there a way to update the keys (columns) of a DictWriter before calling writerow()?

csv.Dictwriter is instantiated thus: csv.Dictwriter实例化为:

 class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

fieldsnames is a sequence of keys, or in my case, a dict. fieldsnames是键序列,在我的情况下是字典。

Here's my question; 这是我的问题; after instantiating DictWriter with a certain dict, I wish to remove some of the keys (and by extension, values) of fieldnames before calling writerow() . 在使用特定的dict实例化DictWriter之后,我希望在调用writerow()之前writerow() fieldnames某些键(并扩展为值writerow() For reasons I won't get into, I can only tell the code which keys to remove after DictWriter has been instantiated. 由于我不愿讨论的原因,我只能告诉代码在实例化DictWriter 之后要删除哪些键。 Dict has just 3 methods: Dict只有3种方法:

writerheader
writerow
writerows

.. none of which are any help. ..这些都没有任何帮助。 Based on my testing, it seems that when DictWriter is instantiated, it sets the column names of the csv-to-be according to fieldnames . 根据我的测试,似乎在实例化DictWriter时,它会根据fieldnames设置将要使用的csv的列名。 And any change made to fieldnames after instantiation has no effect on the column headers that will be generated. 实例化后对fieldnames所做的任何更改都不会影响将要生成的列标题。 Because DictWriter defines the columns at instantiation, am I stuck with these? 因为DictWriter在实例化时定义了列,所以我坚持使用这些列吗? Or is there a way around this? 还是有办法解决?

Suppose you have a dict like - 假设您有一个类似-

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

then you can use csv.writer as follows: 那么您可以按如下方式使用csv.writer:

f = open('abc.csv', 'wb')
csv_writer = csv.writer(f, dialect=csv.excel, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)

for row in rows:
    csv_writer.writerow([row['b'], row['c'])  # Assuming we dont want keys 'a' and 'b' to be written
f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM