如何将行追加到dictwriter python

时间:2017-12-19 10:04:42

标签: python

我有以下代码来创建和编写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中再次指定所有参数?有更清洁的方法吗?

2 个答案:

答案 0 :(得分:1)

这个怎么样?

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

答案 1 :(得分:0)

我相信你应该只使用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')