Platform-independent file paths?

PythonPathCross Platform

Python Problem Overview


How can I use a file inside my app folder in Python? Platform independent of course... something similar to this:

#!/bin/sh
mypath=${0%/*}
LIBDIR=$mypath/modules

Python Solutions


Solution 1 - Python

You can use os.path and its functions, which take care of OS-specific paths:

>>> import os
>>> os.path.join('app', 'subdir', 'dir', 'filename.foo')
'app/subdir/dir/filename.foo'

On Windows, it should print out with backslashes.

Solution 2 - Python

import os
os.path.join(os.path.curdir, 'file.name')

or

import os
os.path.join(os.path.dirname(__file__), 'file.name')

depending upon whether it's a module (2) or a single script (1), and whether you're invoking it from the same directory (1), or from a different one (2).

Edit

Looking at the "attempt" you have in your question, I'd guess that you'd want (1).

Solution 3 - Python

In Python 3.4+ you can use pathlib:

from pathlib import Path

libdir = Path(__file__).resolve().with_name('modules')

How it works: the __file__ attribute contains the pathname of the file from which the module was loaded. You use it to initialize a Path object , make the path absolute using the resolve() method and replace the final path component using the with_name() method.

Solution 4 - Python

__file__ contains the module's location. Use the functions in os.path to extract the directory from it.

Solution 5 - Python

Try this CLR-compliant way:

import os
AppDomain = type('', (object,), {'__init__': (lambda self: self.CurrentDomain = type('', (object,), {'__init__': (lambda self: self.BaseDirectory = os.path.split(__file__)[0])})())})()

Usage:

AppDomain.CurrentDomain.BaseDirectory

Inspired by System.AppDomain in .NET Framework and Core.

Do you know how it works? First off, it imports os. After that, it creates a variable called AppDomain which is set into an instance of a type where its constructor sets its own CurrentDomain to an instance of a type where its constructor sets its own BaseDirectory to the first element in the array returned by os.path.split with the value of __file__ (the module path) as a parameter.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHairoView Question on Stackoverflow
Solution 1 - PythonBlenderView Answer on Stackoverflow
Solution 2 - PythonaviraldgView Answer on Stackoverflow
Solution 3 - PythonEugene YarmashView Answer on Stackoverflow
Solution 4 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 5 - Pythonuser11462042View Answer on Stackoverflow