How can I launch a persistent Playwright browser context in the current directory instead of a system temp folder?

I’m using Playwright with Python and the following code to save a browser context:

user_dir = '/tmp/playwright'

with sync_playwright() as p:
    browser = p.chromium.launch_persistent_context(user_dir, headless=False)
    page = browser.new_page()

This works fine when using /tmp/playwright. However, when I change user_dir to a relative path like ./tmp/playwright, the folders are created, but the Playwright folder remains empty.

How can I correctly launch a persistent context in the current working directory so that data is saved properly?

I ran into the same issue when trying to use a relative path for launch_persistent_context.

Playwright needs the absolute path, otherwise it may create the folder structure but fail to save the browser data. In my setup,

I did this:

import os
from playwright.sync_api import sync_playwright

user_dir = os.path.abspath("./tmp/playwright")

with sync_playwright() as p:
    browser = p.chromium.launch_persistent_context(user_dir, headless=False)
    page = browser.new_page()

After using os.path.abspath, all the user data and session info was correctly saved in the folder. Relative paths alone didn’t work reliably for me.

I faced the same problem and realized Playwright treats relative paths differently depending on where the script is executed.

Using a relative path like ./tmp/playwright sometimes creates the folder but doesn’t persist the profile.

Switching to an absolute path fixed it:

from pathlib import Path
from playwright.sync_api import sync_playwright

user_dir = Path("./tmp/playwright").resolve()

with sync_playwright() as p:
    browser = p.chromium.launch_persistent_context(str(user_dir), headless=False)
    page = browser.new_page()

Now the browser stores cookies, local storage, and other context data correctly.

When I tried using a relative folder for launch_persistent_context, Playwright created empty directories for me.

The trick is to resolve the path to absolute before passing it.

I usually do:

from pathlib import Path
from playwright.sync_api import sync_playwright

user_dir = Path.cwd() / "tmp" / "playwright"

with sync_playwright() as p:
    browser = p.chromium.launch_persistent_context(str(user_dir), headless=False)
    page = browser.new_page()

This approach ensures Playwright knows exactly where to store the persistent context. Also, make sure the folder exists or Playwright has permission to create files there.