【问题标题】:How to append row to dictwriter python如何将行附加到dictwriter python
【发布时间】:2017-12-19 10:04:42
【问题描述】:

我有以下代码来创建和编写 csvfile。

with open("A:\\example_results\\testing.csv", "w") as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames = ['first_name', 'last_name'], dialect="excel", delimiter=";")
            writer.writeheader()
            writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
            writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
            writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

稍后如果我想打开文件并将行追加到其中,我如何获取 dictwriter 并完成这项工作。现在我就是这样,

with open("A:\\example_results\\testing.csv", "a") as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ['first_name', 'last_name'], dialect="excel", delimiter=";")
    writer.writerow({'first_name': 'asdasdasd', 'last_name': 'asdasd'})

但是为什么我要在 DictWriter 中再次指定所有参数呢?有没有更清洁的方法来做到这一点?

【问题讨论】:

  • 以追加模式打开文件并创建一个新的dictwriter来完成这项工作?
  • 但是为什么我要在添加时在 Dictwriter 上再次给出字段名。有没有更简洁的代码来做到这一点
  • 如果你想重复使用同一个 dictwriter,你必须把它保存在某个地方,并且你必须保持文件打开。

标签: python


【解决方案1】:

这个怎么样?

import csv   
with open(r'A:\\example_results\\testing.csv', 'a') as f:
    writer = csv.writer(f, delimiter =';')
    writer.writerow(['111111', '222222222222'])

【讨论】:

  • 不起作用,因为分隔符和标题对齐,方言消失了。
  • 更新了分隔符参数
【解决方案2】:

我相信你应该只使用 append 参数。如果您之前就创建了文件,并且知道其中没有任何内容,那么这种方式会更加方便和清晰。

我愿意。

with open('foo.txt', 'a') as file:
    for _ in xrange(0, 10):
        file.write('Hello World !~\n')

不需要你的 filePath 两次。但是,如果您真的想保持这种状态,我相信您应该这样做......

filePath = 'foo.txt'
# 'write' parameter
with open(filePath, 'w') as file:
    for _ in xrange(0, 10):
        file.write('Hello World !~\n')

# 'append' parameter
with open(filePath, 'a') as file:
    for _ in xrange(0, 10):
        file.write('Hello World !~\n')

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 2018-02-17
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2020-05-23
    • 1970-01-01
    相关资源
    最近更新 更多