python-shutil

主要做用與拷貝文件用的。spa

1.shutil.copyfileobj(文件1,文件2):將文件1的數據覆蓋copy給文件2。日誌

複製代碼
import shutil

f1 = open("1.txt",encoding="utf-8")

f2 = open("2.txt","w",encoding="utf-8")

shutil.copyfileobj(f1,f2)
複製代碼

 

2.shutil.copyfile(文件1,文件2):不用打開文件,直接用文件名進行覆蓋copy。code

import shutil

shutil.copyfile("1.txt","3.txt")

 

 

3.shutil.copymode(文件1,文件2):之拷貝權限,內容組,用戶,均不變。orm

複製代碼
def copymode(src,dst):
    """copy mode bits from src to dst"""
    if hasattr(os,'chmod'):
        st = os.stat(stc)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst,mode)
複製代碼

 

4.shutil.copystat(文件1,文件):只拷貝了權限。對象

複製代碼
def copystat(src,dst):
    """將全部的狀態信息(模式位、時間、時間、標誌)從src複製到dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst,(st.st_atime,st.st_mtime))
    if hasattr(os, 'chmod')
        os.chmod(dst,mode)
    if hasattr(os, 'chflags') and hasattr(st,'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError,why:
            for err in 'EOPNOTSUPP', 'ENOTSUP':
                if hasattr(errno,err) and why.errno == getattr(errno, err):
                    break
                else:
                    raise
複製代碼

 

5.shutil.copy(文件1,文件2):拷貝文件和權限都進行copy。blog

複製代碼
def copy(src,dst):
    """copy data and mode bits ("cp src dst")
    The destination may be a directory.
    """
    if os.path.isdir(dst):
        dst = os.path.join(dst,os.path.basename(src))
        copyfile(src,dst)
        copymode(src,dst)
複製代碼

 

6.shutil.copy2(文件1,文件2):拷貝了文件和狀態信息。遞歸

 

7.shutil.copytree(源目錄,目標目錄):能夠遞歸copy多個目錄到指定目錄下。ip

  • shutil.ignore_patterns(*patterns)
  • shutil.copytree(src, dst, symlinks=False, ignore=None)

遞歸的去拷貝文件utf-8

例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))ci

 

8.shutil.rmtree(目標目錄):能夠遞歸刪除目錄下的目錄及文件。

 

9.shutil.move(源文件,指定路徑):遞歸移動一個文件。

 

10.shutil.make_archive():能夠壓縮,打包文件。

import shutil

shutil.make_archive("shutil_archive_test","zip","D:\新建文件夾 (2)")

11.shutil.make_archive(base_name, format,...)

建立壓縮包並返回文件路徑,例如:zip、tar

    • base_name: 壓縮包的文件名,也能夠是壓縮包的路徑。只是文件名時,則保存至當前目錄,不然保存至指定路徑,
      如:www                        =>保存至當前路徑
      如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    • format: 壓縮包種類,「zip」, 「tar」, 「bztar」,「gztar」
    • root_dir: 要壓縮的文件夾路徑(默認當前目錄)
    • owner: 用戶,默認當前用戶
    • group: 組,默認當前組
    • logger: 用於記錄日誌,一般是logging.Logger對象
1
2
3
4
5
6
7
8
9
#將 /Users/wupeiqi/Downloads/test 下的文件打包放置當前程序目錄
  
import shutil
ret = shutil.make_archive( "wwwwwwwwww" 'gztar' , root_dir= '/Users/wupeiqi/Downloads/test' )
  
  
#將 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目錄
import shutil
ret = shutil.make_archive( "/Users/wupeiqi/wwwwwwwwww" 'gztar' , root_dir= '/Users/wupeiqi/Downloads/test' )

 

shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的,詳細:

zipfile 壓縮解壓

複製代碼
import zipfile

# 壓縮
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解壓
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close()
複製代碼

 

tarfile 壓縮解壓

複製代碼
import tarfile

# 壓縮
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
tar.close()

# 解壓
tar = tarfile.open('your.tar','r')
tar.extractall()  # 可設置解壓地址
tar.close()
複製代碼

 

第二種方法:

import zipfile

z = zipfile.ZipFile("day5.zip","w")

z.write("a")

 

解壓:

z.extractall(「a」)

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息