Using absolute unix paths in windows with python

后端 未结 3 1028
无人共我
无人共我 2020-12-30 21:09

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

相关标签:
3条回答
  • 2020-12-30 21:41

    Ok, I got an answer by myself.

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

    Maybe it will be useful for anybody

    0 讨论(0)
  • 2020-12-30 21:45

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

    print os.path.abspath("/var/lib/blob_files/myfile.blob")
    >>> C:\var\lib\blob_files\myfile.blob
    
    print os.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):
        return os.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))
        if path.startswith("\\"): return "C:" + path
        return path
    
    0 讨论(0)
  • 2020-12-30 21:45

    From Blenders response at Platform-independent file paths?

    >>> import os
    >>> os.path.join('app', 'subdir', 'dir', 'filename.foo')
    'app/subdir/dir/filename.foo'
    
    0 讨论(0)
提交回复
热议问题