shutil -一種高層次的文件操作工具,強大之處是在對文件的復(fù)制與刪除操作支持比較好。
shutil.copyfileobj(fsrc, fdst[, length=16*1024])? ? #copy文件內(nèi)容到另一個文件,可以copy指定大小的內(nèi)容
defcopyfileobj(fsrc, fdst, length=16*1024):"""copy data from file-like object fsrc to file-like object fdst"""while1:
buf=fsrc.read(length)ifnotbuf:breakfdst.write(buf)#注意! 在其中fsrc,fdst都是文件對象,都需要打開后才能進行復(fù)制操作importshutil
f1=open('name','r')
f2=open('name_copy','w+')
shutil.copyfileobj(f1,f2,length=16*1024)
shutil.copyfile(src,dst)? #copy文件內(nèi)容,是不是感覺上面的文件復(fù)制很麻煩?還需要自己手動用open函數(shù)打開文件,在這里就不需要了,事實上,copyfile調(diào)用了copyfileobj
實例:
defcopyfile(src, dst, *, follow_symlinks=True):"""Copy data from src to dst.
If follow_symlinks is not set and src is a symbolic link, a new
symlink will be created instead of copying the file it points to."""if_samefile(src, dst):raiseSameFileError("{!r} and {!r} are the same file".format(src, dst))forfnin[src, dst]:try:
st=os.stat(fn)exceptOSError:#File most likely does not existpasselse:#XXX What about other special files? (sockets, devices...)ifstat.S_ISFIFO(st.st_mode):raiseSpecialFileError("`%s` is a named pipe"%fn)ifnotfollow_symlinksandos.path.islink(src):
os.symlink(os.readlink(src), dst)else:
with open(src,'rb') as fsrc:
with open(dst,'wb') as fdst:
copyfileobj(fsrc, fdst)returndst
刪除目錄使用如下函數(shù):
shutil.rmtree('d:/dd')
移動文件或者文件夾到另外一個地方:
shutil.move('d:/c.png','e:/')
shutil.copystat(src,dst)? ? #復(fù)制所有的狀態(tài)信息,包括權(quán)限,組,用戶,時間等
defcopystat(src, dst, *, follow_symlinks=True):"""Copy all stat info (mode bits, atime, mtime, flags) from src to dst.
If the optional flag `follow_symlinks` is not set, symlinks aren't followed if and
only if both `src` and `dst` are symlinks."""def_nop(*args, ns=None, follow_symlinks=None):pass#follow symlinks (aka don't not follow symlinks)follow = follow_symlinksornot(os.path.islink(src)andos.path.islink(dst))iffollow:#use the real function if it existsdeflookup(name):returngetattr(os, name, _nop)else:#use the real function only if it exists#*and* it supports follow_symlinksdeflookup(name):
fn=getattr(os, name, _nop)iffninos.supports_follow_symlinks:returnfnreturn_nop
st= lookup("stat")(src, follow_symlinks=follow)
mode=stat.S_IMODE(st.st_mode)
lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns),
follow_symlinks=follow)try:
lookup("chmod")(dst, mode, follow_symlinks=follow)exceptNotImplementedError:#if we got a NotImplementedError, it's because#* follow_symlinks=False,#* lchown() is unavailable, and#* either#* fchownat() is unavailable or#* fchownat() doesn't implement AT_SYMLINK_NOFOLLOW.#(it returned ENOSUP.)#therefore we're out of options--we simply cannot chown the#symlink.? give up, suppress the error.#(which is what shutil always did in this circumstance.)passifhasattr(st,'st_flags'):try:
lookup("chflags")(dst, st.st_flags, follow_symlinks=follow)exceptOSError as why:forerrin'EOPNOTSUPP','ENOTSUP':ifhasattr(errno, err)andwhy.errno ==getattr(errno, err):breakelse:raise_copyxattr(src, dst, follow_symlinks=follow)
shutil.copy(src,dst)? #復(fù)制文件的內(nèi)容以及權(quán)限,先copyfile后copymode
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,ignore_dangling_symlinks=False)? #遞歸的復(fù)制文件內(nèi)容及狀態(tài)信息
shutil.rmtree(path, ignore_errors=False, onerror=None)#遞歸地刪除文件
shutil.move(src, dst)? ? #遞歸的移動文件
make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,dry_run=0, owner=None, group=None, logger=None)? #壓縮打包
base_name:? ? 壓縮打包后的文件名或者路徑名
format:????????? 壓縮或者打包格式"zip", "tar", "bztar"or "gztar"
root_dir :???????? 將哪個目錄或者文件打包(也就是源文件)
實例:
>>> shutil.make_archive('tarball','gztar',root_dir='copytree_test')
[root@slyoyo python_test]#ls -ltotal 12drwxr-xr-x. 3 root? root? 4096 May 14 19:36copytree_copy
drwxr-xr-x. 3 root? root? 4096 May 14 19:36copytree_test-rw-r--r--. 1 root? root? ? ? 0 May 14 21:12tarball.tar.gz-rw-r--r--. 1 python python? 79 May 14 05:17test1-rw-r--r--. 1 root? root? ? ? 0 May 14 19:10 test2