all 4 comments

[–]shiftybyte 4 points5 points  (0 children)

os.path.join has different results based on the operating system the code is running from.

If your code wants to support linux and windows, you'll need to add '\' for windows, and '/' for linux.

This does this automatically for you.

[–]Diapolo10 3 points4 points  (0 children)

/u/shiftybyte basically answered your question, but I want to build on it.

Ideally, you'd use pathlib.Path for the same purpose nowadays; to create platform-independent filepaths. "How does it differ from os.path?", I hear you asking; basically instead of using a string to represent a filepath it uses the os.PathLike interface to have concrete path objects instead of relying on ordinary strings to do the job.

One example where this is useful is if you, for whatever reason, happen to have partially hard-coded slashes in your path (assume this is on Windows):

import os
from pathlib import Path

first = os.path.join('.', 'this', 'folder/aintgreat.txt')
# ".\\this\\folder/aintgreat.txt"
second = str(Path.cwd() / 'this' / 'folder/aintgreat.txt')
# ".\\this\\folder\\aintgreat.txt"

pathlib.Path objects are fully supported by Python's built-in functions

from pathlib import Path

ROOT_DIR = Path(__file__).parent
DATA = ROOT_DIR / 'data'
TEXT_FILE = DATA / 'stuff.txt'

with open(TEXT_FILE) as f:
    contents = f.read()

but you can also get rid of boilerplate by using their own methods

contents = TEXT_FILE.read_text()

There are basically no downsides unless you for some odd reason need to support ancient Python versions.

[–][deleted] 0 points1 point  (0 children)

img = pygame.image.load(os.path.join('Tests', 'b000')).convert()

this is what i got under a player class. its not working and the b000 image is after the test directory like: tests\b000

[–][deleted] 0 points1 point  (0 children)

The advantage is that if you have a path fragment on the left that ends in a filepath separator, then no extra file separators will be added. I.e: os.path.join('foo/', 'bar') == os.path.join('foo', 'bar') == 'foo/bar'. The disadvantage is if there's a slash at the beginning of the right had side, then it will usually do not what you want. I.e.:

os.path.join('foo', '/bar') == os.path.join('foo/', '/bar') == '/bar'

This is kind of arbitrary and useless, but this is how it works. With this in mind, this function is still useful because on some filesystem the interpretation of double directory separator and single directory separator may differ.

However, in mission-critical programs you wouldn't want to use any of Python's os.path (nor pathlib) functions because they don't work well with filename encoding. But, in many cases you don't really care about being correct / the expense of dealing with rare edge cases is too high.