PythonIsBae
PythonIsBae

Reputation: 358

CSV DictWriter not moving to next row and deleting previous values

I have this code:

os.truncate('cookies.csv', 0)
fieldnames = ['domain', 'expiry', 'httpOnly', 'name', 'path', 'secure', 'value']


def open_csv(value):
    with open('cookies.csv', 'r+') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writerow(value)

cookie = driver.get_cookie('example cookie')  # get cookie from selenium chrome webdriver
driver.close()
open_csv(cookie)

It should write in this format, values aren't accurate just example:

'domain': google.com, 'expiry': 123456, 'httpOnly': true, 'name': cookie1, 'path':/, 'secure': true, 'value': 123abc
'domain': google.com, 'expiry': 123457, 'httpOnly': true, 'name': cookie2, 'path':/, 'secure': true, 'value': 456def

However, it only writes in the first row, so after writing cookie1 it will then write cookie2 in its place.

Upvotes: 0

Views: 49

Answers (1)

Milan Cermak
Milan Cermak

Reputation: 8074

You need to open the file for appending, using the a+ file mode. See this SO answer for detailed explanation.

Upvotes: 1

Related Questions