0

I am trying to write cookies to a json file.

cookies = web.get_cookies()
with open('test.json', 'w') as outputdata:
    json.dump(cookies, outputdata)
sleep(5)

Which writes cookies to test.json.

I am trying to create a cookie file for each user and each website visited such as.

cookies/{user}/{website}.json

'w' should create a file if it does not exist. But instead of the file being created I am getting error file does not exist.

I have defined the variables, printing user shows the username.

When manually creating the file such as test.json in the first example the script works.

How can I create the file at the path with variables?

Thank you

1 Answer 1

2

'w' does create a file provided the containing directory exists.

You could ensure that the directory exists with os.makedirs:

# create directories if required without error if they exist 
#  thanks to exists_ok=True
os.makedirs(f'cookies/{users}', exist_ok=True)
with os.open(f'cookies/{users}/{website}.json':
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.