genericpath.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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:
  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:
  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:
  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. s1 = min(m)
  56. s2 = max(m)
  57. for i, c in enumerate(s1):
  58. if c != s2[i]:
  59. return s1[:i]
  60. return s1
  61. # Are two stat buffers (obtained from stat, fstat or lstat)
  62. # describing the same file?
  63. def samestat(s1, s2):
  64. """Test whether two stat buffers reference the same file"""
  65. return (s1.st_ino == s2.st_ino and
  66. s1.st_dev == s2.st_dev)
  67. # Are two filenames really pointing to the same file?
  68. def samefile(f1, f2):
  69. """Test whether two pathnames reference the same actual file"""
  70. s1 = os.stat(f1)
  71. s2 = os.stat(f2)
  72. return samestat(s1, s2)
  73. # Are two open files really referencing the same file?
  74. # (Not necessarily the same file descriptor!)
  75. def sameopenfile(fp1, fp2):
  76. """Test whether two open file objects reference the same file"""
  77. s1 = os.fstat(fp1)
  78. s2 = os.fstat(fp2)
  79. return samestat(s1, s2)
  80. # Split a path in root and extension.
  81. # The extension is everything starting at the last dot in the last
  82. # pathname component; the root is everything before that.
  83. # It is always true that root + ext == p.
  84. # Generic implementation of splitext, to be parametrized with
  85. # the separators
  86. def _splitext(p, sep, altsep, extsep):
  87. """Split the extension from a pathname.
  88. Extension is everything from the last dot to the end, ignoring
  89. leading dots. Returns "(root, ext)"; ext may be empty."""
  90. # NOTE: This code must work for text and bytes strings.
  91. sepIndex = p.rfind(sep)
  92. if altsep:
  93. altsepIndex = p.rfind(altsep)
  94. sepIndex = max(sepIndex, altsepIndex)
  95. dotIndex = p.rfind(extsep)
  96. if dotIndex > sepIndex:
  97. # skip all leading dots
  98. filenameIndex = sepIndex + 1
  99. while filenameIndex < dotIndex:
  100. if p[filenameIndex:filenameIndex+1] != extsep:
  101. return p[:dotIndex], p[dotIndex:]
  102. filenameIndex += 1
  103. return p, p[:0]
  104. def _check_arg_types(funcname, *args):
  105. hasstr = hasbytes = False
  106. for s in args:
  107. if isinstance(s, str):
  108. hasstr = True
  109. elif isinstance(s, bytes):
  110. hasbytes = True
  111. else:
  112. raise TypeError('%s() argument must be str or bytes, not %r' %
  113. (funcname, s.__class__.__name__)) from None
  114. if hasstr and hasbytes:
  115. raise TypeError("Can't mix strings and bytes in path components") from None