os.path.join Ignoring First Argument

os.path.join returns only the second argument when it starts with /

Quick Answer

os.path.join() discards all previous components when it encounters an absolute path. Remove the leading slash from the second argument.

Why This Happens

os.path.join() is designed so that if any component is an absolute path, previous components are discarded. This catches developers off guard with user input or config values starting with /.

The Problem

import os
path = os.path.join('/home/user', '/data/file.txt')
# Result: '/data/file.txt'

The Fix

import os
path = os.path.join('/home/user', 'data/file.txt')
# Result: '/home/user/data/file.txt'

# Strip leading slash:
subpath = '/data/file.txt'.lstrip('/')
path = os.path.join('/home/user', subpath)

Step-by-Step Fix

  1. 1

    Remove leading slashes

    Strip leading / from relative path components.

  2. 2

    Use pathlib

    pathlib.Path('/home') / 'data' / 'file.txt' is clearer.

  3. 3

    Validate user input

    Always strip leading separators from relative parts.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free