Python之shutil模块学习(二十一)
shutil模块主要是对文件的高级操作,以及压缩文件等的操作,我们下来先来看该模块的主要方法,以及
该模块的详细的信息介绍,见操作的代码:
#!/usr/bin/env python #-*- coding:utf-8 -* import shutil print dir(shutil) print type(help(shutil))
见执行如上的代码后的输出内容:
C:\Python27\python.exe D:/git/Python/Day/index.py ['Error', 'ExecError', 'SpecialFileError', '_ARCHIVE_FORMATS', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_basename', '_call_external_zip', '_destinsrc', '_get_gid', '_get_uid', '_make_tarball', '_make_zipfile', '_samefile', 'abspath', 'collections', 'copy', 'copy2', 'copyfile', 'copyfileobj', 'copymode', 'copystat', 'copytree', 'errno', 'fnmatch', 'get_archive_formats', 'getgrnam', 'getpwnam', 'ignore_patterns', 'make_archive', 'move', 'os', 'register_archive_format', 'rmtree', 'stat', 'sys', 'unregister_archive_format'] Help on module shutil: NAME shutil - Utility functions for copying and archiving files and directory trees. FILE c:\python27\lib\shutil.py DESCRIPTION XXX The functions here don't copy the resource fork or other metadata on Mac. CLASSES exceptions.EnvironmentError(exceptions.StandardError) Error ExecError SpecialFileError class Error(exceptions.EnvironmentError) | Method resolution order: | Error | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __reduce__(...) | | __str__(...) | x.__str__() <==> str(x) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.EnvironmentError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class ExecError(exceptions.EnvironmentError) | Raised when a command could not be executed | | Method resolution order: | ExecError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __reduce__(...) | | __str__(...) | x.__str__() <==> str(x) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.EnvironmentError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class SpecialFileError(exceptions.EnvironmentError) | Raised when trying to do a kind of operation (e.g. copying) which is | not supported on a special file (e.g. a named pipe) | | Method resolution order: | SpecialFileError | exceptions.EnvironmentError | exceptions.StandardError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from exceptions.EnvironmentError: | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __reduce__(...) | | __str__(...) | x.__str__() <==> str(x) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.EnvironmentError: | | errno | exception errno | | filename | exception filename | | strerror | exception strerror | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.EnvironmentError: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message FUNCTIONS copy(src, dst) Copy data and mode bits ("cp src dst"). The destination may be a directory. copy2(src, dst) Copy data and all stat info ("cp -p src dst"). The destination may be a directory. copyfile(src, dst) Copy data from src to dst copyfileobj(fsrc, fdst, length=16384) copy data from file-like object fsrc to file-like object fdst copymode(src, dst) Copy mode bits from src to dst copystat(src, dst) Copy all stat info (mode bits, atime, mtime, flags) from src to dst copytree(src, dst, symlinks=False, ignore=None) Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory being visited by copytree(), and `names` which is the list of `src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the `src` directory that should not be copied. XXX Consider this example code rather than the ultimate tool. get_archive_formats() Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) ignore_patterns(*patterns) Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None) Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. move(src, dst) Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. register_archive_format(name, function, extra_args=None, description='') Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be returned by the get_archive_formats() function. rmtree(path, ignore_errors=False, onerror=None) Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. unregister_archive_format(name) DATA __all__ = ['copyfileobj', 'copyfile', 'copymode', 'copystat', 'copy', ... <type 'NoneType'> Process finished with exit code 0
下面我们详细的来看shutil模块的常用的方法,以及依据具体的案例,来进行操作,我们先来看把文件内容复制到另外一个
文件,实现文件内容的复制,具体就是我们把config文件夹下的config.ini文件内容复制到log文件夹下的log.md,见实现的代码:
#!/usr/bin/env python #-*- coding:utf-8 -* import shutil import os #实现读取一个文件内容然后复制到另外一个文件 if os.path.exists(os.path.join(os.path.dirname(__file__),'log','log.md')): shutil.copyfileobj(open(os.path.join(os.path.dirname(__file__),'config','config.ini'),'r'), open(os.path.join(os.path.dirname(__file__),'log','log.md'),'w'))
执行代码之后,就会实现文件内容的复制。下来我们来实现copy文件,就是把config文件夹下的config.ini文件copy到log的
文件夹,见实现的代码:
#!/usr/bin/env python #-*- coding:utf-8 -* import shutil import os #实现读取一个文件内容然后复制到另外一个文件 if os.path.exists(os.path.join(os.path.dirname(__file__),'log','config.ini')): print u'config.ini文件已存在log文件夹目录,不需要copy' else: shutil.copyfile(os.path.join(os.path.dirname(__file__),'config','config.ini'), os.path.join(os.path.dirname(__file__),'log','config.ini'))
注释:实现把一个文件从一个目录复制到另外一个文件,也包含了文件内容的,也就是说,copy到新的目录下的文件内容和之前的
文件内容一致。其他常用的方法见如下的代码:
#!/usr/bin/env python #-*- coding:utf-8 -* import shutil import os #拷贝文件和权限 shutil.copy('db.ini','c:/log.db') #仅拷贝权限,内容,组,用户均不会变,不会拷贝文件内容 shutil.copymode('db.ini','') #拷贝状态的信息,包括:moded bits,atime,mtime,flags shutil.copystat() #拷贝文件和状态信息 shutil.copy2() #拷贝文件夹 shutil.copytree('folder1','folder2',ignore=shutil.ignore_patterns('*.py')) #递归删除文件 shutil.rmtree() #重命名文件 shutil.move()
见创建压缩包的程序,见实现的代码:
#!/usr/bin/env python #-*- coding:utf-8 -* import shutil import os #创建文件压缩包并返回路劲 shutil.make_archive('index.py','gztar',root_dir=os.path.dirname(__file__))
注释:执行如上的代码后,会在执行的当前模块的目录下创建index.py.tar.gz的压缩文件。
谢谢您查看我的博客,可扫描如下的二维码关注我的公众号,谢谢!!!
欢迎关注微信公众号“Python自动化测试”