Python os模組學習筆記

來源:互聯網
上載者:User

Python os模組學習筆記

   這篇文章主要介紹了Python os模組學習筆記,本文總結了OS模組的常用方法、實用方法,並給出了兩個使用執行個體,需要的朋友可以參考下

  一、os模組概述

  Python os模組包含普遍的作業系統功能。例如檔案的複製、建立、修改、刪除檔案及檔案夾...

  二、常用方法

  1、os.listdir() 返回指定目錄下的所有檔案和目錄名。

  2、os.remove() 刪除一個檔案。

  3、os.system() 運行shell命令。

  4、os.path.split() 函數返回一個路徑的目錄名和檔案名稱

  5、os.path.isfile()和os.path.isdir() 函數分別檢驗給出的路徑是一個檔案還是目錄,傳回值分別為Ture或False

  6、os.path.exists() 函數用來檢驗給出的路徑是否存在,傳回值分別為Ture或False。

  7、os.path.getsize(name) 獲得檔案大小,如果name是目錄返回0L

  8、os.path.splitext() 分離檔案名稱與副檔名

  9、os.path.join(path,name) 串連目錄與檔案名稱或目錄

  10、os.path.basename(path) 返迴文件名

  11、os.path.dirname(path) 返迴文件路徑

  12、os.walk(path)

  該函數返回一個元組,該元組有3個元素,這3個元素分別表示每次遍曆的路徑名,目錄列表和檔案清單

  os.walk()舉例:

  代碼如下:

  >>> import os

  >>> for root, dirs, files in os.walk("wd/chat", topdown=False):

  ... for name in files:

  ... print(os.path.join(root, name)) #列印檔案絕對路徑

  ... for name in dirs:

  ... print(os.path.join(root, name)) #列印目錄絕對路徑 ...

  執行個體:用python批量修改檔案的副檔名:

  代碼如下:

  import os

  # 列出目前的目錄下所有的檔案

  files = os.listdir(".")

  for filename in files:

  portion = os.path.splitext(filename)

  # 如果尾碼是.txt

  if portion[1] == ".pdb":

  # 重新組合檔案名稱和尾碼名

  newname = portion[0] + ".dssp"

  os.rename(filename,newname)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.