Unix paths that work for any platform in Python?

后端 未结 7 2042
迷失自我
迷失自我 2021-01-04 17:35

Can all paths in a Python program use \"..\" (for the parent directory) and / (for separating path components), and still work whatever the platform?

On one

7条回答
  •  生来不讨喜
    2021-01-04 18:08

    "Almost always safe" is right. All of the platforms you care about probably work ok today and I don't think they will be changing their conventions any time soon.

    However Python is very portable and runs on a lot more than the usual platforms. The reason for the os module is to help smooth things over it a platform does have different requirements.

    Is there a good reason for you to not use the os functions?

    os.pardir is self documenting whereas ".." isn't, and os.pardir might be easier to grep for

    Here is some docs from python 1.6 when Mac was still different for everything

    OS routines for Mac, DOS, NT, or Posix depending on what system we're on.

    This exports: - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc. - os.path is one of the modules posixpath, ntpath, macpath, or dospath - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', or 'ce' - os.curdir is a string representing the current directory ('.' or ':') - os.pardir is a string representing the parent directory ('..' or '::') - os.sep is the (or a most common) pathname separator ('/' or ':' or '\') - os.altsep is the alternate pathname separator (None or '/') - os.pathsep is the component separator used in $PATH etc - os.linesep is the line separator in text files (' ' or ' ' or ' ') - os.defpath is the default search path for executables

    Programs that import and use 'os' stand a better chance of being portable between different platforms. Of course, they must then only use functions that are defined by all platforms (e.g., unlink and opendir), and leave all pathname manipulation to os.path (e.g., split and join).

提交回复
热议问题