python的os模組使用

2021-10-07 15:04:37 字數 1827 閱讀 3112

①檢視os的名字

import os

print(os.name) //nt,'nt'表示windows系統,'posix'表示linux系統

②檢視os環境變數

import os

print(os.environ)

print(os.environ.get('pat', 'default')) //檢視變數'pat',若不存在,則輸出'default'

③檢視絕對路徑

import os

print(os.path.abspath('a.txt')) //c:\users\84572\pycharmprojects\hello\a.txt

print(os.path.abspath('.')) // c:\users\84572\pycharmprojects\hello

④拼接檔案路徑,不需要檔案真的存在,只起到拼接作用

import os

print(os.path.join('d:/', 'test'))  //   d:/test

⑤拆路徑,不需要檔案真的存在,只起到拆除作用

import os

print(os.path.split('d:/a.txt')) //    ('d:/', 'a.txt')

⑥得到檔案的副檔名

import os

print(os.path.splitext('d:/a.txt')) //  ('d:/a', '.txt')

⑦建立、刪除資料夾

import os

os.mkdir('d:/test') //建立

os.rmdir('d:/test')//刪除

os.makedirs("file1/file2/file3")      #建立資料夾目錄. 建立多級目錄

os.mkdir("file")    # 建立資料夾. 但是上級目錄必須存在

os.copy("oldfile","newfile")   #oldfile只能是資料夾,newfile可以是檔案,也可以是目標目錄

os.rename("oldname","newname")   #重新命名檔案(目錄)    檔案或目錄都是使用這條命令

os.removedirs()   # 刪除多級目錄, 要求必須是空的

os.rmdir("dir")    #只能刪除空目錄  

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

os.path.split(path)  #返回乙個路徑的目錄名和檔名   

os.path.dirname()  #獲取路徑名

os.path.basename() #獲取檔名

os.path.getsize(filename) #獲取檔案大小

os.chdir("path")   換路徑

⑧重新命名檔案

import os

print(os.rename('a.txt', 'b.txt'))

⑨刪除模組

import os

print(os.remove('a.txt'))

⑩檢視目錄

import os

print([x for x in os.listdir('d:/') if os.path.isdir(os.path.join('d:/', x))])

print([x for x in os.listdir('.') if os.path.isdir(x)]) //檢視安裝目錄下的檔案

print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py'])//檢視字尾名為.py的檔案

Python內建模組 os模組的使用

os模組是直譯器與作業系統的互動模組,使用os模組 os模組的使用,盡快解決,檔案的增刪改查 import osos.getcwd 獲取當前工作目錄,當前指令碼工作的路徑 os.chdir path 改變當前指令碼工作目錄,相當去cd切換目錄 os.curdir 返回當前目錄 os.pardir 獲...

python常用模組之os模組的使用

os模組是python內建模組,可以作業系統檔案,需要匯入import os 重新命名檔案 import os os.rename src,dst src表示舊檔案或目錄名,dst表示新檔案或目錄名 刪除檔案 os.remove path path表示路徑,只能刪除檔案,如果是目錄就會報錯 建立目錄...

python模組 OS模組

bin env python coding utf 8 import os print os.name 輸出主機平台 print os.getcwd 輸出當前目錄 print os.listdir os.getcwd 輸出當前目錄的檔案 橫向 for i in os.listdir os.getcw...