genericpath.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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', '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. def getsize(filename):
  40. """Return the size of a file, reported by os.stat()."""
  41. return os.stat(filename).st_size
  42. def getmtime(filename):
  43. """Return the last modification time of a file, reported by os.stat()."""
  44. return os.stat(filename).st_mtime
  45. def getatime(filename):
  46. """Return the last access time of a file, reported by os.stat()."""
  47. return os.stat(filename).st_atime
  48. def getctime(filename):
  49. """Return the metadata change time of a file, reported by os.stat()."""
  50. return os.stat(filename).st_ctime
  51. # Return the longest prefix of all list elements.
  52. def commonprefix(m):
  53. "Given a list of pathnames, returns the longest common leading component"
  54. if not m: return ''
  55. # Some people pass in a list of pathname parts to operate in an OS-agnostic
  56. # fashion; don't try to translate in that case as that's an abuse of the
  57. # API and they are already doing what they need to be OS-agnostic and so
  58. # they most likely won't be using an os.PathLike object in the sublists.
  59. if not isinstance(m[0], (list, tuple)):
  60. m = tuple(map(os.fspath, m))
  61. s1 = min(m)
  62. s2 = max(m)
  63. for i, c in enumerate(s1):
  64. if c != s2[i]:
  65. return s1[:i]
  66. return s1
  67. # Are two stat buffers (obtained from stat, fstat or lstat)
  68. # describing the same file?
  69. def samestat(s1, s2):
  70. """Test whether two stat buffers reference the same file"""
  71. return (s1.st_ino == s2.st_ino and
  72. s1.st_dev == s2.st_dev)
  73. # Are two filenames really pointing to the same file?
  74. def samefile(f1, f2):
  75. """Test whether two pathnames reference the same actual file or directory
  76. This is determined by the device number and i-node number and
  77. raises an exception if an os.stat() call on either pathname fails.
  78. """
  79. s1 = os.stat(f1)
  80. s2 = os.stat(f2)
  81. return samestat(s1, s2)
  82. # Are two open files really referencing the same file?
  83. # (Not necessarily the same file descriptor!)
  84. def sameopenfile(fp1, fp2):
  85. """Test whether two open file objects reference the same file"""
  86. s1 = os.fstat(fp1)
  87. s2 = os.fstat(fp2)
  88. return samestat(s1, s2)
  89. # Split a path in root and extension.
  90. # The extension is everything starting at the last dot in the last
  91. # pathname component; the root is everything before that.
  92. # It is always true that root + ext == p.
  93. # Generic implementation of splitext, to be parametrized with
  94. # the separators
  95. def _splitext(p, sep, altsep, extsep):
  96. """Split the extension from a pathname.
  97. Extension is everything from the last dot to the end, ignoring
  98. leading dots. Returns "(root, ext)"; ext may be empty."""
  99. # NOTE: This code must work for text and bytes strings.
  100. sepIndex = p.rfind(sep)
  101. if altsep:
  102. altsepIndex = p.rfind(altsep)
  103. sepIndex = max(sepIndex, altsepIndex)
  104. dotIndex = p.rfind(extsep)
  105. if dotIndex > sepIndex:
  106. # skip all leading dots
  107. filenameIndex = sepIndex + 1
  108. while filenameIndex < dotIndex:
  109. if p[filenameIndex:filenameIndex+1] != extsep:
  110. return p[:dotIndex], p[dotIndex:]
  111. filenameIndex += 1
  112. return p, p[:0]
  113. def _check_arg_types(funcname, *args):
  114. hasstr = hasbytes = False
  115. for s in args:
  116. if isinstance(s, str):
  117. hasstr = True
  118. elif isinstance(s, bytes):
  119. hasbytes = True
  120. else:
  121. raise TypeError(f'{funcname}() argument must be str, bytes, or '
  122. f'os.PathLike object, not {s.__class__.__name__!r}') from None
  123. if hasstr and hasbytes:
  124. raise TypeError("Can't mix strings and bytes in path components") from None