python3_06_01.模塊之os

好車配好輪。


os.environ獲取系統環境變量
os.name字符串指示當前使用平臺。win->'nt'; Linux->'posix'
os.sep操作系統特定的路徑分隔符,win下爲"\\",Linux下爲"/">>> os.getcwd() + os.sep + 'world.txt'
'/tmp/world.txt' 目錄字符串拼接很有用
os.linesep當前平臺使用的行終止符,win下爲"\t\n",Linux下爲"\n"
os.system('top')運行shell命令,直接顯示
os.getcwd()查看當前目錄
切換目錄
os.listdir()列出目錄下所有內容
os.mkdir('test')新建單級目錄test
os.rmdir('test')刪除目錄test,目錄不爲空則報錯
os.removedirs('ceshi/test')遞歸刪除目錄,ceshi也會被刪除,不爲空報錯
os.makedirs('ceshi/test')新建多層遞歸目錄
os.remove('test.txt')刪除文件
os.rename('hello.txt','world.txt')重命名文件/目錄,前爲舊後爲新
os.stat('/tmp/world.txt')獲取文件目錄信息
os.access('/tmp/world.txt',os.F_OK)os.access(path, mode);檢測權限os.F_OK: 作爲access()的mode參數,測試path是否存在。
os.R_OK: 包含在access()的mode參數中 , 測試path是否可讀。
os.W_OK 包含在access()的mode參數中 , 測試path是否可寫。
os.X_OK 包含在access()的mode參數中 ,測試path是否可執行。
os.chmod()用於更改文件或目錄的權限。http://www.runoob.com/python/os-chmod.html
os.chown(path, uid, gid);用於更改文件所有者,如果不修改可以設置爲 -1
os.chroot()更改當前進程的根目錄爲指定的目錄,使用該函數需要管理員權限。
os.path.abspath("world.txt")返回絕對路徑返回結果: '/tmp/world.txt'
os.path.basename("/tmp/world.txt")返回文件名返回結果: 'world.txt'
os.path.isabs("world.txt")如果是絕對路徑,返回True返回結果: False
os.path.isdir("/usr")如果path是一個存在的目錄,則返回True。否則返回False返回結果: True
os.path.isfile("world.txt")如果path是一個存在的文件,返回True。否則返回False返回結果: True
os.path.split("/var/log/messages")把路徑分割爲文件名 和 目錄名返回結果 : ('/var/log', 'messages')
os.path.dirname("/var/log/messages")獲取文件的上級目錄返回結果: '/var/log'
os.path.join(path1[, path2[, ...]])將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略,這個必會,日後用途非常廣泛!請看下面實例
#linux下查找文件
def find_file(name,start='/'):
for relpath,dirs,files in os.walk(start):
    if name in files:
    full_path = os.path.join(start,relpath,name)
    file_path = os.path.normpath(os.path.abspath(full_path))
   return file_path


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章