Skip to content Skip to sidebar Skip to footer

Using Absolute Unix Paths In Windows With Python

I'm creating an application that stores blob files into the hard drive, but this script must run in both linux and windows, the issue is that i want to give it an absolute path fro

Solution 1:

Use os.path.abspath(), and also os.path.expanduser() for files relative to the user's home directory:

printos.path.abspath("/var/lib/blob_files/myfile.blob")
>>> C:\var\lib\blob_files\myfile.blob

printos.path.abspath(os.path.expanduser("~/blob_files/myfile.blob"))
>>> C:\Users\jerry\blob_files\myfile.blob

These will "do the right thing" for both Windows and POSIX paths.

expanduser() won't change the path if it doesn't have a ~ in it, so you can safely use it with all paths. Thus, you can easily write a wrapper function:

import os
def fixpath(path):
    returnos.path.abspath(os.path.expanduser(path))

Note that the drive letter used will be the drive specified by the current working directory of the Python process, usually the directory your script is in (if launching from Windows Explorer, and assuming your script doesn't change it). If you want to force it to always be C: you can do something like this:

import os
def fixpath(path):
    path = os.path.normpath(os.path.expanduser(path))
    ifpath.startswith("\\"): return"C:" + pathreturnpath

Solution 2:

Ok, I got an answer by myself.

os.path.exists(os.path.abspath(filePath))

Maybe it will be useful for anybody

Solution 3:

From Blenders response at Platform-independent file paths?

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

Post a Comment for "Using Absolute Unix Paths In Windows With Python"