shutil Is a relatively powerful python Package of operation files for
pip install shutil
This is a more commonly used function
1.1 shutil.copy(src, dst)
# The return value is the path after replication
shutil.copy(' Source address ', ' Destination address ')
1.2 shutil.copy2(src, dst)
and shutil.copy() almost , The copied results retain all the original information ( Include status information )
1.3 shutil.copyfile()
Copy the contents of one file into another file , The target file does not need to exist
# The return value is the path after replication
shutil.copyfile(' Source document ', ' Target file ')
1.4 shutil.copyfileobj(fsrc, fdst[,length=16*1024]))
Copy the contents of one file into another file , You can specify the content size
( Use less )
shutil.copyfileobj(open(' Source document ','r'),open(' Target file ','w'))
1.5 shutil.copytree(src, dst, symlinks=False, ignore=None)
Copy the entire file directory
( Whether the folder is empty or not , Can be copied , And all the contents in the folder will be copied , Destination directory cannot exist )
The third parameter is if True, The symbolic link under the folder will be maintained when copying the directory , yes False, Then a physical copy will be generated in the replicated directory to replace the symbolic connection .
ignore Means to exclude , such as ignore=shutil.ignore_patterns(‘.pyc’, 'tmp’)
shutil.copytree(' Source directory ',' Target directory ', True, )
2.1 shutil.rmtree()
Deleted folder , If you delete a file os.unlink(path)
Recursively remove the entire directory , Whether empty or not
shutil.rmtree(' Directory path ')
move()
shutil.move(' Source address ',' Destination address ')
shutil.make_archive(base_name, format,...)
Create a zip and return the file path , for example :zip、tar
''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :711312441 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
# take /data Package and place the current program directory under
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
# take /data Package and place files under /tmp/ Catalog
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')
# zipfile Compression and decompression
import zipfile
# Compress
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()
# decompression
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall(path='.')
z.close()
# tarfile
import tarfile
# Compress
>>> t=tarfile.open('/tmp/egon.tar','w')
>>> t.add('/test1/a.py',arcname='a.bak')
>>> t.add('/test1/b.py',arcname='b.bak')
>>> t.close()
# decompression
>>> t=tarfile.open('/tmp/egon.tar','r')
>>> t.extractall('/egon')
>>> t.close()