Python中的os模組

2021-07-08 15:01:17 字數 2119 閱讀 4259

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是目錄返回0l

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):返回檔案路徑 

os.remove()函式用來刪除乙個檔案

1.重新命名:os.rename(old, new)        2.刪除:os.remove(file)                    3.列出目錄下的檔案:os.listdir(path)

4.獲取當前工作目錄:os.getcwd()        5.改變工作目錄:os.chdir(newdir)          6.建立多級目錄:os.makedirs(r"c:\python\test")

7.建立單個目錄:os.mkdir("test")      8.刪除多個目錄:os.removedirs(r"c:\python") #刪除所給路徑最後乙個目錄下所有空目錄。

9.刪除單個目錄:os.rmdir("test")        10.獲取檔案屬性:os.stat(file)          11.修改檔案許可權與時間戳:os.chmod(file)

12.執行作業系統命令:os.system("dir")  13.啟動新程序:os.exec(), os.execvp()      14.在後台執行程式:osspawnv()

15.終止當前程序:os.exit(), os._exit()

16.分離檔名:os.path.split(r"c:\python\hello.py") --> ("c:\\python", "hello.py")

17.分離副檔名:os.path.splitext(r"c:\python\hello.py") --> ("c:\\python\\hello", ".py")

18.獲取路徑名:os.path.dirname(r"c:\python\hello.py") --> "c:\\python"

19.獲取檔名:os.path.basename(r"r:\python\hello.py") --> "hello.py"

20.判斷檔案是否存在:os.path.exists(r"c:\python\hello.py") --> true

21.判斷是否是絕對路徑:os.path.isabs(r".\python\") --> false

22.判斷是否是目錄:os.path.isdir(r"c:\python") --> true

23.判斷是否是檔案:os.path.isfile(r"c:\python\hello.py") --> true

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

26.*******:os.ismount("c:\\") --> true

27.搜尋目錄下的所有檔案:os.path.walk() 

shutil模組對檔案的操作:

1.複製單個檔案:shultil.copy(oldfile, newfle)

2.複製整個目錄樹:shultil.copytree(r".\setup", r".\backup")

3.刪除整個目錄樹:shultil.rmtree(r".\backup") 

python中的os模組

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

python中的os模組

os.makedirs dirname1 dirname2 可生成多層遞迴目錄 os.removedirs dirname1 若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推 os.mkdir dirname 生成單級目錄 相當於shell中mkdir dirname os.rm...

python中的OS模組

coding utf 8 import os,sys 列印當前工作路徑 a os.getcwd 改變當前的工作路徑 a os.chdir c 列印當前目錄下的所有檔案或資料夾 print os.listdir 創乙個資料夾 os.mkdir grils 0o777 print os.listdir ...