python之os模組總結

2021-10-11 14:30:45 字數 3147 閱讀 2863

os模組簡單的來說它是乙個python的系統程式設計的操作模組,可以用來幫助我們處理檔案和目錄的作用,下面準備了一些os模組在日常比較常用的方法。

首先我們需要先導入os模組:

import os
輸出當前系統平台:

print

(os.name)

>>

>

'nt'

#若是windows則輸出'nt',若是linux/unix,則是'posix'

輸出當前目錄:

print

(os.getcwd())

>>

>e:\python\selenium\learn\pythonfirst

更改執行環境目錄:

print

(os.getcwd(

))

os.chdir(r'e:\python\selenium\learn\pythonfirst\pythonfile'

)#更改執行環境目錄

print

(os.getcwd())

>>

>e:\python\selenium\learn\pythonfirst

>>

>e:\python\selenium\learn\pythonfirst\pythonfile

建立資料夾

os.mkdir(

'test'

)# 當前路徑建立資料夾test

刪除當前空資料夾

os.rmdir(

'test'

)

建立遞迴目錄

os.makedirs(r'e:\python\selenium\learn\pythonfirst\a\b\c'

)

刪除遞迴空目錄資料夾

os.removedirs(r'e:\python\selenium\learn\pythonfirst\a\b\c'

)

修改檔名

os.rename(

'a.txt'

,'b.txt'

)

獲取目錄下的資料夾及檔案

print

(os.listdir())

# 當前目錄

print

(os.listdir(r'e:\python\selenium\learn'))

# 指定目錄

刪除檔案

os.remove(r'e:\python\selenium\learn\pythonfirst\b.txt'

)

執行dos命令(cmd終端執行命令)

list1 = os.popen(

'pip list'

)#獲取pip安裝的第三方庫列表

for i in list1:

print

(i)os.system(

'start .'

)# 開啟當前目錄資料夾

檔案與路徑分開

str

= os.path.split(r'e:\python\selenium\learn\pythonfirst\a.txt'

)>>

>

('e:\\python\\selenium\\learn\\pythonfirst'

,'a.txt'

)

檢驗路徑是否存在

os.path.exists(r'e:\python'

)>>

>

true

檢驗是檔案還是目錄

os.path.isdir(r'e:\python'

)# 檢驗是否是目錄

os.path.isfile(r'e:\python'

)# 檢驗是否是檔案

獲取絕對路徑

os.path.abspath(

'.')

# 當前絕對路徑

os.path.abspath(

'..'

)#上級目錄絕對路徑

os.path.abspath(r'.\firstapi.py'

)# 該檔案絕對路徑

分離檔名與副檔名

print

(os.path.splitext(

'a.txt'))

>>

>

('a'

,'.txt'

)

只獲取檔名

print

(os.path.basename(r'e:\python\selenium\learn\pythonfirst\a.txt'))

>>

>a.txt

只返回目錄

print

(os.path.dirname(r'e:\python\selenium\learn\pythonfirst\a.txt'))

>>

>e:\python\selenium\learn\pythonfirst

獲取檔案大小

print

(os.stat(

'a.txt'

).st_size)

>>

>

60# 單位為kb

print

(os.path.getsize(r'e:\python\selenium\learn\pythonfirst\test.yaml'))

>>

>

60# 單位為kb

python之os模組總結

os模組提供了乙個輕便的方法使用要依賴作業系統的功能,整合了常用的檔案與資料夾操作。os.getcwd os.chdir os.path.split os.path.splitext os.path.splitdriver os.path.realpath path return the absol...

Python模組之 OS模組

一 os模組概述 python os模組包含普遍的作業系統功能。如果你希望你的程式能夠與平台無關的話,這個模組是尤為重要的。一語中的 二 常用方法 1 os.name 輸出字串指示正在使用的平台。如果是window 則用 nt 表示,對於linux unix使用者,它是 posix 2 os.get...

python常用模組之os模組

os模組可以處理檔案和目錄這些日常手動需要做的操作,比如常用的刪除檔案等。此外,os不受平台限制,非常方便。常用功能 1 os.name 顯示當前使用的平台 import os print os.name nt windows2 os.getcwd 顯示當前python指令碼工作路徑 print o...