genericpath.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """
  2. Path operations common to more than one OS
  3. Do not use directly. The OS specific modules import the appropriate
  4. functions from this module themselves.
  5. """
  6. import os
  7. import stat
  8. __all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime',
  9. 'getsize', 'isdir', 'isfile', 'islink', 'samefile', 'sameopenfile',
  10. 'samestat']
  11. # Does a path exist?
  12. # This is false for dangling symbolic links on systems that support them.
  13. def exists(path):
  14. """Test whether a path exists. Returns False for broken symbolic links"""
  15. try:
  16. os.stat(path)
  17. except (OSError, ValueError):
  18. return False
  19. return True
  20. # This follows symbolic links, so both islink() and isdir() can be true
  21. # for the same path on systems that support symlinks
  22. def isfile(path):
  23. """Test whether a path is a regular file"""
  24. try:
  25. st = os.stat(path)
  26. except (OSError, ValueError):
  27. return False
  28. return stat.S_ISREG(st.st_mode)
  29. # Is a path a directory?
  30. # This follows symbolic links, so both islink() and isdir()
  31. # can be true for the same path on systems that support symlinks
  32. def isdir(s):
  33. """Return true if the pathname refers to an existing directory."""
  34. try:
  35. st = os.stat(s)
  36. except (OSError, ValueError):
  37. return False
  38. return stat.S_ISDIR(st.st_mode)
  39. # Is a path a symbolic link?
  40. # This will always return false on systems where os.lstat doesn't exist.
  41. def islink(path):
  42. """Test whether a path is a symbolic link"""
  43. try:
  44. st = os.lstat(path)
  45. except (OSError, ValueError, AttributeError):
  46. return False
  47. return stat.S_ISLNK(st.st_mode)
  48. def getsize(filename):
  49. """Return the size of a file, reported by os.stat()."""
  50. return os.stat(filename).st_size
  51. def getmtime(filename):
  52. """Return the last modification time of a file, reported by os.stat()."""
  53. return os.stat(filename).st_mtime
  54. def getatime(filename):
  55. """Return the last access time of a file, reported by os.stat()."""
  56. return os.stat(filename).st_atime
  57. def getctime(filename):
  58. """Return the metadata change time of a file, reported by os.stat()."""
  59. return os.stat(filename).st_ctime
  60. # Return the longest prefix of all list elements.
  61. def commonprefix(m):
  62. "Given a list of pathnames, returns the longest common leading component"
  63. if not m: return ''
  64. # Some people pass in a list of pathname parts to operate in an OS-agnostic
  65. # fashion; don't try to translate in that case as that's an abuse of the
  66. # API and they are already doing what they need to be OS-agnostic and so
  67. # they most likely won't be using an os.PathLike object in the sublists.
  68. if not isinstance(m[0], (list, tuple)):
  69. m = tuple(map(os.fspath, m))
  70. s1 = min(m)
  71. s2 = max(m)
  72. for i, c in enumerate(s1):
  73. if c != s2[i]:
  74. return s1[:i]
  75. return s1
  76. # Are two stat buffers (obtained from stat, fstat or lstat)
  77. # describing the same file?
  78. def samestat(s1, s2):
  79. """Test whether two stat buffers reference the same file"""
  80. return (s1.st_ino == s2.st_ino and
  81. s1.st_dev == s2.st_dev)
  82. # Are two filenames really pointing to the same file?
  83. def samefile(f1, f2):
  84. """Test whether two pathnames reference the same actual file or directory
  85. This is determined by the device number and i-node number and
  86. raises an exception if an os.stat() call on either pathname fails.
  87. """
  88. s1 = os.stat(f1)
  89. s2 = os.stat(f2)
  90. return samestat(s1, s2)
  91. # Are two open files really referencing the same file?
  92. # (Not necessarily the same file descriptor!)
  93. def sameopenfile(fp1, fp2):
  94. """Test whether two open file objects reference the same file"""
  95. s1 = os.fstat(fp1)
  96. s2 = os.fstat(fp2)
  97. return samestat(s1, s2)
  98. # Split a path in root and extension.
  99. # The extension is everything starting at the last dot in the last
  100. # pathname component; the root is everything before that.
  101. # It is always true that root + ext == p.
  102. # Generic implementation of splitext, to be parametrized with
  103. # the separators
  104. def _splitext(p, sep, altsep, extsep):
  105. """Split the extension from a pathname.
  106. Extension is everything from the last dot to the end, ignoring
  107. leading dots. Returns "(root, ext)"; ext may be empty."""
  108. # NOTE: This code must work for text and bytes strings.
  109. sepIndex = p.rfind(sep)
  110. if altsep:
  111. altsepIndex = p.rfind(altsep)
  112. sepIndex = max(sepIndex, altsepIndex)
  113. dotIndex = p.rfind(extsep)
  114. if dotIndex > sepIndex:
  115. # skip all leading dots
  116. filenameIndex = sepIndex + 1
  117. while filenameIndex < dotIndex:
  118. if p[filenameIndex:filenameIndex+1] != extsep:
  119. return p[:dotIndex], p[dotIndex:]
  120. filenameIndex += 1
  121. return p, p[:0]
  122. def _check_arg_types(funcname, *args):
  123. hasstr = hasbytes = False
  124. for s in args:
  125. if isinstance(s, str):
  126. hasstr = True
  127. elif isinstance(s, bytes):
  128. hasbytes = True
  129. else:
  130. raise TypeError(f'{funcname}() argument must be str, bytes, or '
  131. f'os.PathLike object, not {s.__class__.__name__!r}') from None
  132. if hasstr and hasbytes:
  133. raise TypeError("Can't mix strings and bytes in path components") from None