1. 程式人生 > >3Python標準庫系列之os模塊

3Python標準庫系列之os模塊

system python command creating provides

Python標準庫系列之os模塊


This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module


os模塊常用方法


模塊方法說明
os.getcwd()獲取當前工作目錄,即當前python腳本工作的目錄路徑
os.chdir(“dirname”)改變當前腳本工作目錄;相當於shell下cd
os.curdir返回當前目錄: (‘.’)
os.pardir獲取當前目錄的父目錄字符串名:(‘..’)
os.makedirs(‘dirname1/dirname2’)可生成多層遞歸目錄
os.removedirs(‘dirname1’)若目錄為空,則刪除,並遞歸到上一級目錄,如若也為空,則刪除,依此類推
os.mkdir(‘dirname’)生成單級目錄;相當於shell中mkdir dirname
os.rmdir(‘dirname’)刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname
os.listdir(‘dirname’)列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印
os.remove()刪除一個文件
os.rename(“oldname”,”newname”)重命名文件/目錄
os.stat(‘path/filename’)獲取文件/目錄信息
os.sep輸出操作系統特定的路徑分隔符,win下為\\,Linux下為/
os.linesep輸出當前平臺使用的行終止符,win下為\t\n,Linux下為\n
os.pathsep輸出用於分割文件路徑的字符串
os.name輸出字符串指示當前使用平臺。win->nt
; Linux->posix
os.system(“bash command”)運行shell命令,直接顯示
os.environ獲取系統環境變量
os.path.abspath(path)返回path規範化的絕對路徑
os.path.split(path)將path分割成目錄和文件名二元組返回
os.path.dirname(path)返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path)返回path最後的文件名。如何path以\結尾,那麽就會返回空值。即os.path.split(path)的第二個元素
os.path.exists(path)如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)如果path是絕對路徑,返回True
os.path.isfile(path)如果path是一個存在的文件,返回True。否則返回False
os.path.isdir(path)如果path是一個存在的目錄,則返回True。否則返回False
os.path.join(path1[, path2[,…]])將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略
os.path.getatime(path)返回path所指向的文件或者目錄的最後存取時間
os.path.getmtime(path)返回path所指向的文件或者目錄的最後修改時間


常用方法實例

獲取當前工作目錄

 # 獲取的進入python時的目錄
 >>> os.getcwd()
‘/root‘


改變工作目錄到/tmp

 # 當前目錄是/root
 >>> os.getcwd()
‘/root‘
 # 切換到/tmp下
 >>> os.chdir("/tmp")
 # 當前目錄變成了/tmp
 >>> os.getcwd()     
‘/tmp‘


獲取/root目錄下的所有文件,包括隱藏文件

 >>> os.listdir(‘/root‘)
[‘.cshrc‘, ‘.bash_history‘, ‘.bash_logout‘, ‘.viminfo‘, ‘.bash_profile‘, ‘.tcshrc‘, ‘scripts.py‘, ‘.bashrc‘, ‘modules‘]


刪除/tmp目錄下的os.txt文件

 >>> os.chdir("/tmp") 
 >>> os.getcwd()     
‘/tmp‘
 >>> os.listdir(‘./‘)   
[‘.ICE-unix‘, ‘yum.log‘]
 >>> os.remove("yum.log")
 >>> os.listdir(‘./‘)    
[‘.ICE-unix‘]


查看/root目錄信息

 >>> os.stat(‘/root‘)        
posix.stat_result(st_mode=16744, st_ino=130817, st_dev=2051L, st_nlink=3, st_uid=0, st_gid=0, st_size=4096, st_atime=1463668203, st_mtime=1463668161, st_ctime=1463668161)


查看當前操作系統的平臺

 >>> os.name
‘posix‘

win —> nt,Linux -> posix


執行一段shell命令

  # 執行的命令要寫絕對路徑
 >>> os.system("/usr/bin/whoami")    
root
# 0代表命令執行成功,如果命令沒有執行成功則返回的是非0
0


組合一個路徑

 >>> a1 = "/"
 >>> a2 = "root"
 >>> os.path.join(a1, a2)
‘/root‘

#Python標準庫 #Os

3Python標準庫系列之os模塊