os模組是python內建模組,可以作業系統檔案,需要匯入import os
重新命名檔案:
刪除檔案:import os
os.rename(src,dst)
#src表示舊檔案或目錄名,dst表示新檔案或目錄名
建立目錄:os.remove(path)
# path表示路徑,只能刪除檔案,如果是目錄就會報錯
os.mkdir(
'file01'
)# mkdir生成目錄時,如果父級目錄不存在則報錯
#例如os.mkdir(
建立多級目錄:
os.makedirs(
'file01/file02/file03'
,exist_ok =
true
)# 遞迴建立目錄,如果目錄已存在則報錯,可使用exist_ok = true使其不報錯,父級不存在也可以建立
# 例如
刪除目錄:
os.rmdir(path)
# path表示要刪除的目錄路徑,只能刪除單層空目錄,不會刪除父級目錄
刪除多級目錄:
os.removedirs(path)
#path表示要刪除的目錄,遞迴刪除,直到目錄中還有其他檔案時停止
例如,當資料夾格式如下時
使用os.rmdir
os.rmdir(
"file01/file03/file04"
)# 只會刪除file04
使用os.removedirs
os.removedirs(
"file01/file03/file04"
)# 遞迴刪除,file01下還有file02,所以不會刪除file01
獲取當前所在目錄:
os.getcwd(
)
獲取目錄列表:
os.listdir(path)
# 例如
切換當前指令碼工作目錄:
os.chdir(path)
# path為目標路徑
# 例如
判斷檔案或資料夾是否存在:
os.path.exits(path)
返回bool值
判斷是否為檔案:
os.path.isfile(path)
返回bool值
判斷是否為目錄:
os.path.isdir(path)
返回bool值
獲取絕對路徑:
os.path.abspath(path)
# 返回path的絕對路徑
# 例如
判斷是否為絕對路徑:
os.path.isabs(path)
#例如print
獲取路徑中的最後部分:
os.path.basename(path)
#例如print
(os.path.basename(
"e:/python/新建資料夾/file01/file02"
))
os.path.dirname(path)
# 不管最後是檔案還是資料夾,都只獲取父目錄部分
# 例如
print
(os.path.dirname(
"e:/python/新建資料夾/file01/file02"
目錄的拼接:
os.path.join(path,
*paths)
# 例如
print
(__file__)
print
(os.path.join(os.path.dirname(__file__)
,"file01"))
print
(os.path.join(os.path.dirname(__file__)
,"/file01"))
# 加斜槓會被作為根目錄
python常用模組之os模組
os模組可以處理檔案和目錄這些日常手動需要做的操作,比如常用的刪除檔案等。此外,os不受平台限制,非常方便。常用功能 1 os.name 顯示當前使用的平台 import os print os.name nt windows2 os.getcwd 顯示當前python指令碼工作路徑 print o...
python常用模組之os
os模組是python與作業系統進行互動的乙個介面 os模組中的方法os.getcwd 獲取當前工作目錄,即當前python指令碼工作的目錄路徑 os.chdir dirname 改變當前指令碼工作目錄 相當於shell下cd os.curdir 返回當前目錄 os.pardir 獲取當前目錄的父目...
Python模組之 OS模組
一 os模組概述 python os模組包含普遍的作業系統功能。如果你希望你的程式能夠與平台無關的話,這個模組是尤為重要的。一語中的 二 常用方法 1 os.name 輸出字串指示正在使用的平台。如果是window 則用 nt 表示,對於linux unix使用者,它是 posix 2 os.get...