1. 程式人生 > >python第九章元件檔案

python第九章元件檔案

  1. 批量操作具有相同型別的檔案(python實現自動化)
    shutil 或者稱為shell工具,該模組中包含一些函式,用於實現python程式中複製,移動、改名和刪除檔案
    shutil.copy(source, destination) 將路徑source處的檔案複製到路徑destination處的資料夾,兩個引數都是字串,當distiantion是一個檔名的時候,表示被複制過來的檔案新名字,返回一個字串表示被複制檔案的路徑。
    shutil.copytree()複製整個資料夾,同樣是兩個引數。包括它下面所有的資料夾和檔案;返回一個字串,是新複製的資料夾的路徑。
  2. shutil.move(source, destination)將路徑sorce處的資料夾移動到路徑destination處,並返回新位置的絕對路徑的字串。(使用的時候注意是否要覆蓋原有的檔案:存在的情況下)。如果要移動的資料夾不存在,那麼就會將原來的檔案改名為目的地的資料夾的名字為檔名,所以在移動檔案之前要先確定要移動到的目的地是資料夾是存在的。
  3. 刪除檔案和資料夾
    os.unlink(path)將刪除path處的檔案
    os.rmdir(path_將刪除path處的資料夾,但是該資料夾必須為空
    shutil.rmtree(path)將刪除path處的資料夾,它包含的所有檔案和資料夾都會被刪除。(不可恢復)
  4. send2trash模組: 安全刪除檔案或者資料夾,它是將刪除的東西放在回收站了。send2trash.send2trash()
    pip install send2trash 的時候報錯:failed to create process/fatal error in launcher
    因為我本地安裝了python2   和python3 
    使用python2 -m pip install send2trash或者python3 -m pip install send2trash即可安裝
  5. 遍歷目錄樹os.wals()函式傳入一個引數:資料夾的路徑,遍歷整個目錄樹,返回三個值:
    當前資料夾名稱的字串(for迴圈當前的資料夾)
    當前資料夾中子資料夾的字串列表
    當前資料夾中檔案的字串的列表。
  6. zipfile模組壓縮檔案:將多個檔案打包成一個檔案,這個檔案叫做歸檔檔案。
    使用過程:
    a、呼叫ZipFile()函式,建立一個ZipFile物件: exampleZip = zipfile.ZipFile(‘file.zip‘
    b、物件的namelist()方法,返回ZIP檔案中包含的所有檔案和資料夾的字串列表。
    import zipfile, os
    
    dir_path = os.getcwd()
    
    file_path = dir_path + '/' + 'zip.zip'
    
    exampleZip = zipfile.ZipFile(file_path)
    
    tmp = exampleZip.namelist()
    print(tmp)
    
    spamInfor = exampleZip.getinfo('zip/1.txt')
    print(spamInfor.file_size)
    print(spamInfor.compress_size)
    
    exampleZip.close()
    
    
    依次列印結果是:
    ['zip/', 'zip/1.txt', 'zip/2.txt', 'zip/3.txt', 'zip/4.txt', 'zip/5.json']
    3742
    1897
  7. 解壓縮: ZipFile物件的extractall()方法用來解壓檔案
    dir_path = os.getcwd()
    file_path = dir_path + '/' + 'zip.zip'
    exampleZip = zipfile.ZipFile(file_path)
    exampleZip.extractall()
    exampleZip.close()

    extract(引數)方法用於從ZIP檔案中解壓單個檔案。傳遞的引數必須是namelist()返回的字串列表中的一個,第二個引數可選用於指定解壓的位置。

  8. 建立和新增到ZIP檔案,必須以寫模式開啟ZipFile物件,w作為第二個引數。
    import os, zipfile
    
    dir_path = os.getcwd()
    newZip = zipfile.ZipFile('new.zip', 'w')
    newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)
    newZip.close()
    

    write()方法的第二個引數是指壓縮型別,寫模式會擦除ZIP檔案中原有的內容,可以像open一樣使用追加模式a

  9. 總結
    備註:在刪除檔案的是最好先註釋掉刪除,換成列印,看看到底要刪除哪些檔案,確保刪除是安全的。