永成的學習部落格

這裡會記錄永成學習的一部分

0%

使用shutil、os模組協助複製、移動、刪除、新增目錄或檔案

使用shutil、os模組協助複製、移動、刪除、新增目錄或檔案

⬇⬇⬇文章開始⬇⬇⬇

shutil模組

  • 安裝模組:
    1
    pip install pytest-shutil
  1. 複製資料夾所有檔案至新建資料夾內

    1
    2
    3
    shutil.copytree('A','B')
    # A和B都可能是目錄位置,但B必須為不存在
    # shutil.copytree會自動產生B目錄,如果B目錄存在會出現錯誤訊息。
    • 參考寫法
      1
      2
      import shutil
      shutil.copytree('./test1/','D:/test2/')
  2. 刪除目錄及目錄內所有檔案

    1
    2
    import shutil
    shutil.rmtree('./test/')
  3. 複製文件

    1
    2
    3
    import shutil
    shutil.copyfile('A','B')
    # A和B只能是檔案,不能是目錄位址
    • 參考寫法
      1
      shutil.copyfile('test1.jpg','test2.jpg')
  4. 複製目錄或者複製目錄內的檔案

    1
    2
    3
    import shutil
    shutil.copy('A','B')
    # A只能是目錄,B可以是目錄或檔案
  5. 移動文件

    1
    2
    3
    import shutil
    shutil.move('A','B')
    # A可以是目錄或檔案,B只能是目錄

os模組

不必安裝,內建模組

  1. 刪除單個文件

    1
    2
    import os
    os.remove('test.jpg')
  2. 判斷資料夾(目錄)是否存在

    1
    2
    3
    import os
    if not os.path.isdir('./test/'):
    print('資料夾不存在')
  3. 新增資料夾(單層目錄)

    1
    2
    import os
    os.mkdir('./test/')
  4. 新增資料夾(多層目錄)
    如果前一層test資料夾不存在,將會自動新建

    1
    2
    3
    import os
    os.makedirs('./test/hello/',exist_ok=True)
    # os.makedirs的exist_ok預設為False,如果資料夾存在的話,將會發生錯誤訊息,因此要記得修改為True,無論目錄是否存在,都會自動判斷新增。
  5. 合併目錄位址

    1
    2
    import os
    os.path.join('./test/','hello,jpg')
    • 輸出為./test/hello,jpg

     

    1
    2
    import os
    os.path.join('./testA/','./testB/,'hello.jpg')
    • 輸出為./testA/testB/hello.jpg