python 目錄檔案

來源:互聯網
上載者:User

標籤:shu   getcwd   copyfile   執行個體   nbsp   bin   isl   擷取路徑   size   

每天寫一點,總有一天我這條鹹魚能變得更鹹

 

python 中對檔案及目錄的操作基本依賴與os,shutil模組,其中以os模組為主,最主要的幾個方法執行個體如下:

1.判斷檔案/目錄是否存在(os.path.exists(filename)),執行個體如下:

  

 

檔案存在則返回True,不存在則返回False

 

2.擷取當前檔案路徑(os.getcwd()),執行個體如下:

 

3.刪除檔案(os.remove()),執行個體如下:

刪除檔案需確保檔案確實存在

 

 4.修改檔案/目錄名(os.rename()),執行個體如下:

修改檔案名稱需要確定檔案存在

5.遍曆目錄下的所有檔案(os.walk),執行個體如下:

 1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import os 4  5  6 for dirs,paths,names in os.walk(os.getcwd()): 7     for path in paths: 8         print path 9 10     for name in names:11         print os.path.join(dirs,path,name)

輸出如下:

 1 .idea 2 D:\test_his\.idea\a.txt 3 D:\test_his\.idea\b.txt 4 D:\test_his\.idea\main.py 5 D:\test_his\.idea\scrpy.py 6 D:\test_his\.idea\test.py 7 D:\test_his\.idea\test1.py 8 inspectionProfiles 9 D:\test_his\.idea\inspectionProfiles\encodings.xml10 D:\test_his\.idea\inspectionProfiles\misc.xml11 D:\test_his\.idea\inspectionProfiles\modules.xml12 D:\test_his\.idea\inspectionProfiles\test_his.iml13 D:\test_his\.idea\inspectionProfiles\workspace.xml14 D:\test_his\.idea\inspectionProfiles\inspectionProfiles\profiles_settings.xml

 

 其餘方法和函數簡介如下:

名稱 作用 備忘
os.listdir(filedir) 返回指定目錄下的所有檔案名稱和目錄名 目錄存在
os.removedirs(r‘filedir‘) 刪除多個目錄 目錄存在
os.path.getsize(filename) 擷取檔案大小  
os.path.splitext(filename) 分離尾碼名 分離最後一個.符號後面的前後內容
os.path.isfile() 判斷是否為檔案  
os.path.isdir() 判斷是否為目錄  
os.path.split() 分離檔案目錄和檔案名稱  
os.path.dirname() 擷取路徑名  
os.path.islink() 是否存在連結  
os.mkdir() 建立目錄  
os.makedirs() 建立多個目錄  
os.chmod() 修改許可權  
os.stat 擷取檔案屬性  
shutil.copyfile() 拷貝檔案  
shutil.copy(file,path) 拷貝檔案到目錄  
shutil.copytree(path,newpath) 拷貝整個目錄  
shutil.move() 移動檔案或者目錄  
shutil.rmtree(dir) 刪除目錄  

python 目錄檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.