While using Playwright’s launch_persistent_context method, the goal is to save the browser context in the current working directory instead of the default /tmp/playwright path. When setting user_dir = './tmp/playwright', the folders get created, but the playwright directory remains empty after execution. Why does this happen, and how can you correctly configure launch_persistent_context to store browser data (like cookies, cache, and session info) in the local directory where the script is executed?
Ah, I’ve run into this myself a few times. The thing is, launch_persistent_context expects an absolute path for the user data directory. If you pass something like './tmp/playwright', Playwright interprets it relative to its internal process, not necessarily your script’s current working directory. That’s why the folder may appear empty.
A quick fix is using Python’s os.path.abspath() to make it absolute:
from playwright.sync_api import sync_playwright
import os
with sync_playwright() as p:
user_dir = os.path.abspath("./playwright_data") # absolute path
browser = p.chromium.launch_persistent_context(
user_dir,
headless=False
)
page = browser.new_page()
page.goto("https://example.com")
browser.close()
Now all browser data—cookies, cache, sessions—gets saved inside ./playwright_data in your current directory."
Just to add a little nuance from my experience, even with an absolute path, Playwright won’t automatically create nested directories. So if you specify something like './tmp/playwright' but tmp doesn’t exist yet, it can silently default elsewhere (like /tmp/playwright).
The safe way is to create the full path first:
import os
os.makedirs("tmp/playwright", exist_ok=True)
Then you can launch your persistent context:
browser = p.chromium.launch_persistent_context("tmp/playwright", headless=False)
This guarantees that launch_persistent_context will save all your browser data locally, exactly where you want it.
Adding a final piece from my own testing: even with a correct path, you might notice your directory still looks empty. That’s because launch_persistent_context doesn’t immediately flush session data while the browser is running. Cookies, IndexedDB, and other storage are only written when the context closes gracefully.
So make sure your script ends with:
browser.close()
After that, the directory will contain all session data. Then, reopening the same directory in a future run will restore your session perfectly. It’s a subtle thing, but it saves a lot of headaches."