I have preferred the following utility function. Show
It converts both variations (linux style and windows style) to linux style. Both windows and linux supports '/' separator in python. I rejected the simplistic os.sep.join(['str','str','str']) because it does not take into account existing separators. Take the following case with sep.join vs vanilla join:
The vanilla join could be repaired with the suggested:
So far so good. But then we introduce the following scenario where we will be interacting with linux from windows.
The above will then fail because the sftp server expects a '/' separator while os.path.normpath will on windows normalize to '\'. By using the pjoin utility function or similar, it will work cross OS, web, ftp, etc. Sergey sergey at mighty.co.zaSun Jul 31 18:52:58 CEST 2011
Nice! That's what I've been expecting. Thanks. Your one string command is tiny and complete. And elegant. Final desicion? Or it could be something better and more professional? So we have removed regexps and everything is fine now. Yes? On Mon, 01 Aug 2011 02:37:09 +1000 Steven D'Aprano <steve at pearwood.info> wrote > Sergey wrote: > > Gotcha! > > http://pymon.googlecode.com/svn/tags/pymon-0.2/Internet/rsync.py > > 231-239 strings > > > > ## code ## > > > > def convertPath(path): > > # Convert windows, mac path to unix version. > > separator = os.path.normpath("/") > > if separator != "/": > > path = re.sub(re.escape(separator), "/", path) > > The above code is buggy. It doesn't work as expected on a classic Mac. > Hint: import macpath; print macpath.normpath('/') > > Besides, there is no need to use the 20 lb sledgehammer of regular > expressions to crack the tiny little peanut of replacing a simple > character with another simple character. > > The above function is much more sensibly written as: > > def convertPath(path): > separator = os.path.sep > if sep != '/': > path = path.replace(os.path.sep, '/') > return path > > Or even more simply: > > return path.replace(os.path.sep, '/') > > (although that may do a small amount of unnecessary work on Unix systems). > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ South Africas premier free email service - www.webmail.co.za For super low premiums, click here http://www.dialdirect.co.za/?vdn=15828
More information about the Tutor mailing list Source code: Lib/posixpath.py (for POSIX) and Lib/ntpath.py (for Windows). This module implements some useful functions on pathnames. To read or write files see Unlike
a unix shell, Python does not do any automatic path expansions. Functions such as See also The Note All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned. Note Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The
Changed in version 3.8: os.path. abspath (path)¶
Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function os.path. basename (path)¶Return the base name of pathname path. This is the second element of the pair returned by passing path to the function os.path. commonpath (paths)¶Return the longest common sub-path of each pathname in the sequence paths. Raise Availability: Unix, Windows. New in version 3.5. os.path. commonprefix (list)¶Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string ( Note This function may return invalid paths because it works a
character at a time. To obtain a valid path, see >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib']) '/usr/l' >>> os.path.commonpath(['/usr/lib', '/usr/local/lib']) '/usr' os.path. dirname (path)¶Return the directory name of pathname
path. This is the first element of the pair returned by passing path to the function os.path. exists (path)¶Return Changed in version 3.3: path can now be an integer: os.path. lexists (path)¶Return os.path. expanduser (path)¶On Unix and Windows, return the argument with
an initial component of On Unix, an initial On Windows, If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged. Changed in version 3.8: No longer uses os.path. expandvars (path)¶Return the argument with environment variables expanded. Substrings of the form On Windows, os.path. getatime (path)¶Return the time of last access of path. The return value is a floating point number giving the number of seconds since the epoch (see the
os.path. getmtime (path)¶Return the time of last modification of path. The return value is a floating point number giving the number of seconds since the epoch (see the os.path. getctime (path)¶Return the system’s ctime which, on
some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path. The return value is a number giving the number of seconds since the epoch (see the os.path. getsize (path)¶Return the size, in bytes, of path. Raise os.path. isabs (path)¶Return os.path. isfile (path)¶Return os.path. isdir (path)¶Return os.path. islink (path)¶Return os.path. ismount (path)¶Return New in version 3.4: Support for detecting non-root mount points on Windows. os.path. join (path, *paths)¶Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component. On Windows, the drive letter is not reset when an absolute path component (e.g., Changed in version 3.6: Accepts a path-like object for path and paths. os.path. normcase (path)¶Normalize the case of a pathname. On Windows, convert all characters in the pathname to lowercase, and also convert forward slashes to backward slashes. On other operating systems, return the path unchanged. os.path. normpath (path)¶
Note
os.path. realpath (path, *,
strict=False)¶Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system). If a path doesn’t exist or a symlink loop is encountered, and strict is Note This function emulates the operating system’s procedure for making a path canonical, which differs slightly between Windows and UNIX with respect to how links and subsequent path components interact. Operating system APIs make paths canonical as needed, so it’s not normally necessary to call this function. Changed in version 3.8: Symbolic links and junctions are now resolved on Windows. Changed in version 3.10: The strict parameter was added. os.path. relpath (path,
start=os.curdir)¶Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start. On Windows,
start defaults to Availability: Unix, Windows. os.path. samefile (path2, path2)¶Return Availability: Unix, Windows. Changed in version 3.2: Added Windows support. Changed in version 3.4: Windows now uses the same implementation as all other platforms. os.path. sameopenfile (fp1, fp2)¶Return Availability: Unix, Windows. Changed in version 3.2: Added Windows support. os.path. samestat (stat1, stat2)¶Return Availability: Unix, Windows. Changed in version 3.4: Added Windows support. os.path. split (path)¶Split the pathname path into a pair, os.path. splitdrive (path)¶Split the pathname path into a pair On Windows, splits a pathname into drive/UNC sharepoint and relative path. If the path contains a drive letter, drive will contain everything up to and including the colon: >>> splitdrive("c:/dir") ("c:", "/dir") If the path contains a UNC path, drive will contain the host name and share, up to but not including the fourth separator: >>> splitdrive("//host/computer/dir") ("//host/computer", "/dir") os.path. splitext (path)¶Split the pathname path into a pair If the path contains no extension, ext will be >>> splitext('bar') ('bar', '') If the path contains an extension, then ext will be set to this extension, including the leading period. Note that previous periods will be ignored: >>> splitext('foo.bar.exe') ('foo.bar', '.exe') >>> splitext('/foo/bar.exe') ('/foo/bar', '.exe') Leading periods of the last component of the path are considered to be part of the root: >>> splitext('.cshrc') ('.cshrc', '') >>> splitext('/foo/....jpg') ('/foo/....jpg', '') os.path. supports_unicode_filenames ¶
What is os path SEP in Python?os.sep. The character used by the operating system to separate pathname components. This is '/' for POSIX and '\' for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use os.
What does os path Sep do?os. path. sep or os. sep returns the character used by the operating system to separate pathname components.
How do I change the path in Python?To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
What is os path Abspath?The os. path. abspath() is a built-in Python function that returns a normalized absolute version of the pathname, which means the abspath() function returns the pathname to a path passed as a parameter.
|