source: vendor/python/2.5/Lib/shutil.py@ 3232

Last change on this file since 3232 was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 5.8 KB
Line 
1"""Utility functions for copying files and directory trees.
2
3XXX The functions here don't copy the resource fork or other metadata on Mac.
4
5"""
6
7import os
8import sys
9import stat
10from os.path import abspath
11
12__all__ = ["copyfileobj","copyfile","copymode","copystat","copy","copy2",
13 "copytree","move","rmtree","Error"]
14
15class Error(EnvironmentError):
16 pass
17
18def copyfileobj(fsrc, fdst, length=16*1024):
19 """copy data from file-like object fsrc to file-like object fdst"""
20 while 1:
21 buf = fsrc.read(length)
22 if not buf:
23 break
24 fdst.write(buf)
25
26def _samefile(src, dst):
27 # Macintosh, Unix.
28 if hasattr(os.path,'samefile'):
29 try:
30 return os.path.samefile(src, dst)
31 except OSError:
32 return False
33
34 # All other platforms: check for same pathname.
35 return (os.path.normcase(os.path.abspath(src)) ==
36 os.path.normcase(os.path.abspath(dst)))
37
38def copyfile(src, dst):
39 """Copy data from src to dst"""
40 if _samefile(src, dst):
41 raise Error, "`%s` and `%s` are the same file" % (src, dst)
42
43 fsrc = None
44 fdst = None
45 try:
46 fsrc = open(src, 'rb')
47 fdst = open(dst, 'wb')
48 copyfileobj(fsrc, fdst)
49 finally:
50 if fdst:
51 fdst.close()
52 if fsrc:
53 fsrc.close()
54
55def copymode(src, dst):
56 """Copy mode bits from src to dst"""
57 if hasattr(os, 'chmod'):
58 st = os.stat(src)
59 mode = stat.S_IMODE(st.st_mode)
60 os.chmod(dst, mode)
61
62def copystat(src, dst):
63 """Copy all stat info (mode bits, atime and mtime) from src to dst"""
64 st = os.stat(src)
65 mode = stat.S_IMODE(st.st_mode)
66 if hasattr(os, 'utime'):
67 os.utime(dst, (st.st_atime, st.st_mtime))
68 if hasattr(os, 'chmod'):
69 os.chmod(dst, mode)
70
71
72def copy(src, dst):
73 """Copy data and mode bits ("cp src dst").
74
75 The destination may be a directory.
76
77 """
78 if os.path.isdir(dst):
79 dst = os.path.join(dst, os.path.basename(src))
80 copyfile(src, dst)
81 copymode(src, dst)
82
83def copy2(src, dst):
84 """Copy data and all stat info ("cp -p src dst").
85