Python os.path路径模块中的操作方法总结
解析路徑路徑解析依賴與os中定義的一些變量:
- os.sep-路徑各部分之間的分隔符。
- os.extsep-文件名與文件擴展名之間的分隔符。
- os.pardir-路徑中表示目錄樹上一級的部分。
- os.curdir-路徑中當前目錄的部分。
split()函數(shù)將路徑分解為兩個單獨的部分,并返回包含這些結果的tuple。第二個元素是路徑的最后部分,地一個元素是其他部分。
import os.path for path in [ '/one/two/three','/one/two/three/','/','.','']:print '%15s : %s' % (path, os.path.split(path))輸入參數(shù)以os.sep結尾時,最后一個元素是空串。
輸出:
/one/two/three : ('/one/two', 'three') /one/two/three/ : ('/one/two/three', '')/ : ('/', ''). : ('', '.'): ('', '')basename()函數(shù)返回的值等價與split()值的第二部分。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os.path for path in [ '/one/two/three','/one/two/three/','/','.','']:print '%15s : %s' % (path, os.path.basename(path))整個路徑會剝除到只剩下最后一個元素。
輸出:
/one/two/three : three /one/two/three/ : / : . : .:dirname()函數(shù)返回分解路徑得到的第一部分。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os.path for path in [ '/one/two/three','/one/two/three/','/','.','']:print '%15s : %s' % (path, os.path.dirname(path))將basename()與dirname()結合,得到原來的路徑。
/one/two/three : /one/two /one/two/three/ : /one/two/three/ : /. : :splitext()作用類似與split(),不過它會根據(jù)擴展名分隔符而不是目錄分隔符來分解路徑。import os.path
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' for path in [ '/one.txt','/one/two/three.txt','/','.','''two.tar.gz']:print '%21s : %s' % (path, os.path.splitext(path))查找擴展名時,只使用os.extsep的最后一次出現(xiàn)。
/one.txt : ('/one', '.txt')/one/two/three.txt : ('/one/two/three', '.txt')/ : ('/', ''). : ('.', '')two.tar.gz : ('two.tar', '.gz')commonprefix()取一個路徑列表作為參數(shù),返回一個字符串,表示所有路徑中出現(xiàn)的公共前綴。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os.path paths = [ '/one/two/three','/one/two/threetxt','/one/two/three/four',] for path in paths:print 'PATH:', pathprint print 'PREFIX:', os.path.commonprefix(paths)輸出:
PATH: /one/two/three PATH: /one/two/threetxt PATH: /one/two/three/fourPREFIX: /one/two/three建立路徑除了分解現(xiàn)有路徑外,還需要從其他字符串建立路徑,使用join()。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os.path for parts in [ ('one', 'two', 'three'),('\one', 'two', 'three'),('/one', '/two', '/three', '/four'),]:print parts, ':', os.path.join(*parts)如果要連接的某個參數(shù)以os.sep開頭,前面所有參數(shù)都會丟棄,參數(shù)會返回值的開始部分。
('one', 'two', 'three') : one\two\three ('\\one', 'two', 'three') : \one\two\three ('/one', '/two', '/three', '/four') : /four規(guī)范化路徑使用join()或利用嵌入變量由單獨的字符串組合路徑時,得到的路徑最后可能會有多余的分隔符或者相對路徑部分,使用normpath()可以清除這些內容。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os.path for path in [ 'one/two/three','one/./two/three','one/../alt/two/three',]:print '%20s : %s' % (path, os.path.normpath(path))可以計算并壓縮有os.curdir和os.pardir構成的路徑段。
one/two/three : one\two\threeone/./two/three : one\two\three one/../alt/two/three : alt\two\three要把一個相對路徑轉換為一個絕對文件名,可以使用abspath()。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os.path for path in [ '.','..','one/two/three','one/./two/three','one/../alt/two/three',]:print '%20s : %s' % (path, os.path.abspath(path))結果是從一個文件系統(tǒng)樹最頂層開始的完整路徑。
. : C:\Users\Administrator\Desktop.. : C:\Users\Administratorone/two/three : C:\Users\Administrator\Desktop\one\two\threeone/./two/three : C:\Users\Administrator\Desktop\one\two\three one/../alt/two/three : C:\Users\Administrator\Desktop\alt\two\three文件時間
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os import time print 'File:', __file__ print 'Access time:', time.ctime(os.path.getatime(__file__)) print 'Modified time:', time.ctime(os.path.getmtime(__file__)) print 'Change time:', time.ctime(os.path.getctime(__time__)) print 'Size:', os.path.getsize(__file__)返回訪問時間,修改時間,創(chuàng)建時間,文件中的數(shù)據(jù)量。
測試文件程序遇到一個路徑名,通常需要知道這個路徑的一些信息。
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os.path filename = r'C:\Users\Administrator\Desktop\tmp' print 'File :', filename print 'Is file? :', os.path.isfile(filename) print 'Absoulute :', os.path.isabs(filename) print 'Is dir? :', os.path.isdir(filename) print 'Is link? :', os.path.islink(filename) print 'Mountpoint? :', os.path.ismount(filename) print 'Exists? :', os.path.exists(filename) print 'Link Exists? :', os.path.lexists(filename)所有測試都返回布爾值。
File : C:\Users\Administrator\Desktop\tmp Is file? : False Absoulute : True Is dir? : True Is link? : False Mountpoint? : False Exists? : True Link Exists? : True遍歷一個目錄樹
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import os import os.path import pprint def visit(arg, dirname, names):print dirname, argfor name in names:subname = os.path.join(dirname, name)if os.path.isdir(subname):print '%s/' % name else:print ' %s' % nameprint if not os.path.exists('example'):os.mkdir('example') if not os.path.exists('example/one'):os.mkdir('example/one') with open('example/one/file.txt', 'wt') as f:f.write('i love you') with open('example/one/another.txt', 'wt') as f:f.write('i love you, two') os.path.walk('example', visit, '(User data)')會生成一個遞歸的目錄列表。
1 example (User data) 2 one/ 3 4 example\one (User data) 5 another.txt 6 file.txt一些實際的用法合集:
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' #創(chuàng)建文件: os.mknod("test.txt") 創(chuàng)建空文件 fp = open("test.txt",w) 直接打開一個文件,如果文件不存在則創(chuàng)建文件#獲取擴展名: >>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1:] ('.mp4',) >>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1] '.mp4'#獲取文件名: >>> print os.path.basename(r'/root/hahaha/123.txt') 123.txt >>> print os.path.dirname(r'/root/hahaha/123.txt') /root/hahaha#判斷目錄或文件的存在: >>> os.path.exists('/root/1.py') True >>> os.path.exists('/root/') True >>> os.path.exists('/root') True >>> os.path.isdir('/root') True#改變工作目錄: >>> os.chdir('/home') >>> os.getcwd() '/home'#字符串分割: >>> '/usr/bin/env'.split('/') ['', 'usr', 'bin', 'env']#獲取文件夾大小(Python2.x): import os from os.path import join, getsize def getdirsize(dir): size = 0L for root, dirs, files in os.walk(dir): size += sum([getsize(join(root, name)) for name in files]) return size if __name__ == '__main__':filesize = getdirsize('/tmp') print 'There are %.3f' % (filesize/1024/1024), 'Mbytes in /tmp' #獲取文件夾大小(Python3.x): import os from os.path import join, getsize def getdirsize(dir): size = 0 for root, dirs, files in os.walk(dir): size += sum([getsize(join(root, name)) for name in files]) return size if __name__ == '__main__':filesize = getdirsize('/tmp') print ('There are ' + str(filesize/1024/1024) + 'Mbytes in /tmp')總結
以上是生活随笔為你收集整理的Python os.path路径模块中的操作方法总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python引用模块和查找模块路径
- 下一篇: Python中模块(Module)和包(