python中的os模組使用方法

2021-12-29 22:32:43 字數 1871 閱讀 6035

#-*-coding:utf-8

'''os.getcwd():得到當前的目錄

os.listdir('g:\\python2') 獲得g盤python2目錄下的所有內容

os.system():執行shell命令,os.system('cmd'):起動dos

os.remove('g:\\file\\file.txt'):刪除乙個檔案,不能刪除乙個目錄

os.sep 可以取代作業系統特定的路徑分割符。

os.mkdir(os.path.normpath('g:\\file'):建立乙個目錄

#os.path模組

os.path.split('g:\\file\\file.txt'):返回乙個路徑的目錄名和檔名(以元組的形式,因此可以遍歷)

os.path.splitext('file.py'):分離檔名和副檔名,返回的是('file','.py')以元組的方式返回

os.path.exists(''):用來檢驗給出的路徑是否真實存在,若存在返回true

os.path.getsize('g:\\file\\file.txt'):獲得檔案的大小,如果是目錄則返回0

os.path.normpath(name):規範路徑的字串形式,用與儲存檔案

os.path.basename(name):返回的是檔名,如os.path.basename('g:\\file\\file.py'):return file.py

os.path.dirname(path):返回的是檔案的路徑 :如os.path.dirname('g:\\file\\file.txt') return g:\\file

'''import os

#os.system('cmd')

print os.getcwd() #獲得當前的路徑

print os.name #獲得當前作業系統

print os.listdir('g:\\python2')

print os.listdir('g://python2_workspace')

os.path.isfile()和os.path.isdir()函式分別檢驗給出的路徑是乙個檔案還是目錄。

python的os模組使用

檢視os的名字 import os print os.name nt,nt 表示windows系統,posix 表示linux系統 檢視os環境變數 import os print os.environ print os.environ.get pat default 檢視變數 pat 若不存在,則...

Python中的os模組

os.listdir dirname 列出dirname下的目錄和檔案 os.getcwd 獲得當前工作目錄 os.curdir 返回當前目錄 os.chdir dirname 改變工作目錄到dirname os.path.isdir name 判斷name是不是乙個目錄,name不是目錄就返回fa...

python中的os模組

os模組提供了非常豐富的方法用來處理檔案和目錄。1os.access path,mode 檢驗許可權模式 2os.chdir path 改變當前工作目錄 3os.chflags path,flags 設定路徑的標記為數字標記。4os.chmod path,mode 更改許可權 5os.chown p...