OS路徑模組命令

2022-08-28 10:12:09 字數 1201 閱讀 4057

os.remove():刪除指定檔案

os.rmdir():刪除指定目錄

os.mkdir():建立單級目錄

os.makedirs():建立多級目錄

os.listdir(dirname):列出dirname下的目錄和檔案

os.getcwd():獲得當前工作目錄

os.curdir:返回當前目錄('.')

os.chdir(dirname):改變工作目錄到dirname

os.path.isdir(name):判斷name是不是乙個目錄,name不是目錄就返回false

os.path.isfile(name):判斷name是不是乙個檔案,不存在name也返回false

os.path.exists(name):判斷是否存在檔案或目錄name

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

os.path.abspath(name):獲得絕對路徑

os.path.normpath(path):規範path字串形式

os.path.split(name):分割檔名與目錄(事實上,如果你完全使用目錄,

它也會將最後乙個目錄作為檔名而分離,同時它不會判斷檔案或目錄是否存在)

os.path.splitext():分離檔名與副檔名

os.path.join(path,name):連線目錄與檔名或目錄

os.path.basename(path):返回檔名

os.path.dirname(path):返回檔案路徑

# 輸入資料夾路徑,遞迴讀取資料夾內檔名稱

def print_directory_contents(spath):

for child in os.listdir(spath):

#listdir()只是顯示檔名,而不是路徑

child_path = os.path.join(spath, child)

if os.path.isdir(child_path):

print_directory_contents(child_path)

else:

print child_path

if __name__ == '__main__':

print_directory_contents('c:\users\administrator\desktop\pic')

os模組關於路徑

os模組關於路徑的幾個主要方法 os.path 模組路徑訪問函式 os.path.basename 去掉目錄路徑,返回檔名 os.path.dirname 去掉檔名,返回目錄路徑 os.path.split 將路徑分為 dirname,basename 元組os.path.join 將目錄路徑和檔案...

os模組關於路徑

os模組關於路徑的幾個主要方法 os.path 模組路徑訪問函式 os.path.basename 去掉目錄路徑,返回檔名 os.path.dirname 去掉檔名,返回目錄路徑 os.path.split 將路徑分為 dirname,basename 元組 os.path.join 將目錄路徑和檔...

os模組 檔案路徑

1.檔案所在絕對路徑 file d program os.path.abspath file d program 注意 os.getcwd 返回當前工作目錄,當工作目錄與檔案實際所在路徑不同時,返回結果與os.path.abspath 返回結果不同2.檔案所在資料夾路徑 os.path.dirnam...