python os module and the module shutil

Operating system platform property or method

os.name:Windows is nt, linux is POSIX.

os.uname (), linux display

sys.platform, window display win32, linux show Linux.

os.listdir ( "o: / temp"), returns the contents of the directory list.

os also open, read, write method, but the level is too low, it is recommended to use built-in functions open, read, write method, using a similar method.

shutil module

Before learning of the file copy, the use of open two file objects, and then read the contents of the source file, the target file is written to complete the copy process, but this loss stat data information (permissions), etc., because there is no copy this information in the past. Directory Replication how should I do? Python provides a convenient library shutil (Advanced file operations)

copy Copy

copyfileobj (fsrc, fdst, length), copy, fsrc and fdst file object is an open file object open, copy the contents, fdst requirements can be written. length specifies the size of the buffer.

import shutil
with open("test1.txt",mode = "r+",encoding = "utf-8") as f1:
    f1.write("abcd\n1234")
    f1.flush()
    with open("test2.txt",mode = "w+",encoding = "utf-8") as f2:
        shutil.copyfileobj(f1,f2)

结果为:
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-23-36d248eaac3f> in <module>
      4     f1.flush()
      5     with open("test2.txt",mode = "w+",encoding = "utf-8") as f2:
----> 6         shutil.copyfileobj(f1,f2)

f:\Anaconda3\lib\shutil.py in copyfileobj(fsrc, fdst, length)
     77     """copy data from file-like object fsrc to file-like object fdst"""
     78     while 1:
---> 79         buf = fsrc.read(length)
     80         if not buf:
     81             break

f:\Anaconda3\lib\codecs.py in decode(self, input, final)
    320         # decode input (taking the buffer into account)
    321         data = self.buffer + input
--> 322         (result, consumed) = self._buffer_decode(data, self.errors, final)
    323         # keep undecoded input until the next call
    324         self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 0: invalid start byte

 copyfile(src,dst,*,follow-symlinks = True)

Copy the contents of the file does not contain metadata, src, dst string file path.

Call essentially copyfileobj, it is not content with metadata binary copy.

copymode(src,dst*,follow_symlinks = True)

Just copy the permissions.

 

copystat(src,dst,*,follow_symlinks = True)

Copy metadata, stat include permission.

 

 copy(src,dst,*,follow_symlinks =True)

Copy the contents of the documents, permissions, and part of the metadata, not including creation and modification times.

Essentially calling

copyfile(src,dst,fillow_symlinks)

copymode(src,dst,follow_symlinks = follow_symlinks)

copy2 more copy all metadata, but requires platform support than copy.

Essentially calling

copyfile(src,dst,fillow_symlinks = follow_symlinks)

copystat(src,dst,follow_symlinks = follow_symlinks)

copytree (src, dst, symlinks = True, ignore = Noe, copy_function = copy2, ignore_dangling_symlinks = False) recursive copy directories. Default copy2, that is, with more meta-data replication.

src.dst must be a directory, src must exist, dst must not exist.

ignore = func, a callable (src, name) -> ignore_names. Provide a function that will be called, is the source src directory, names as a result of os.listdir (src), is listed in the src file name, the return value is the type of data to be filtered src file name.

import shutil

#f盘xpc下有a,b目录

def ignore(src,names):
    ig = filter(lambda x:x.startswith("a"),names)#忽略a
    return set(ig)

shutil.copytree("e:/xpc","e:/tt/e",ignore=ignore)

结果为:
E:\tt\e\b
e盘下tt目录下的e目录复制了b目录,a被忽略。

rm删除

shutil.rmtree(path,ignore_errors = False,onerror = None)

递归删除,如同rm-rf一样危险,慎用。

它不是院子操作,有可能删除错误,就会中断,已经删除的就删除了。

ignore_errores为True,忽略错误,当为False或者omitted时onerror生效。

onerror为callable,接受函数function、path、execinfo。

shutil.rmtree("f:xpc")#类似rm -rf

move移动

move(src,dst,copy_function = copy2)

递归移动文件、目录到目标,返回目标。

本身使用的是os.rename方法。

如果不支持rename,如果是目录则想copytree再删除源目录。

默认使用copy2方法。

 

 shutil还有打包功能,生成tar并压缩,支持zip,gz.bz,xz。

Guess you like

Origin www.cnblogs.com/xpc51/p/11748676.html