Python文件系統——os.path

6.1 os.path——平臺獨立的文件名管理

解析,構建,測試以及處理文件名和路徑。
6.1.1 解析路徑
路徑解析依賴與os中定義的一些變量:
os.sep-路徑各部分之間的分隔符。
os.extsep-文件名與文件擴展名之間的分隔符。
os.pardir-路徑中表示目錄樹上一級的部分。
os.curdir-路徑中當前目錄的部分。
split()函數將路徑分解爲兩個單獨的部分,並返回包含這些結果的tuple。第二個元素是路徑的最後部分,地一個元素是其餘部分。
import os.path
for path in [ '/one/two/three',
                '/one/two/three/',
                '/',
                '.',
                '']:
    print '%15s : %s' % (path, os.path.split(path))
輸入參數以os.sep結尾時,最後一個元素是空串。
>>> ================================ RESTART ================================
>>> 
 /one/two/three : ('/one/two', 'three')
/one/two/three/ : ('/one/two/three', '')
              / : ('/', '')
              . : ('', '.')
                : ('', '')
basename()函數返回的值等價與split()值的第二部分。
import os.path
for path in [ '/one/two/three',
                '/one/two/three/',
                '/',
                '.',
                '']:
    print '%15s : %s' % (path, os.path.basename(path))
整個路徑會剝除到只剩下最後一個元素。
>>> ================================ RESTART ================================
>>> 
 /one/two/three : three
/one/two/three/ : 
              / : 
              . : .
                : 
dirname()函數返回分解路徑獲得的第一部分。
import os.path
for path in [ '/one/two/three',
                '/one/two/three/',
                '/',
                '.',
                '']:
    print '%15s : %s' % (path, os.path.dirname(path))
將basename()與dirname()結合,獲得原來的路徑。
>>> ================================ RESTART ================================
>>> 
 /one/two/three : /one/two
/one/two/three/ : /one/two/three
              / : /
              . : 
                : 
splitext()做用相似與split(),不過它會根據擴展名分隔符而不是目錄分隔符來分解路徑。
import os.path

for path in [ '/one.txt',
                '/one/two/three.txt',
                '/',
                '.',
                ''
                'two.tar.gz']:
    print '%21s : %s' % (path, os.path.splitext(path))
查找擴展名時,只使用os.extsep的最後一次出現。
>>> ================================ RESTART ================================
>>> 
             /one.txt : ('/one', '.txt')
   /one/two/three.txt : ('/one/two/three', '.txt')
                    / : ('/', '')
                    . : ('.', '')
           two.tar.gz : ('two.tar', '.gz')
commonprefix()取一個路徑列表做爲參數,返回一個字符串,表示全部路徑中出現的公共前綴。
import os.path
paths = [ '/one/two/three',
            '/one/two/threetxt',
            '/one/two/three/four',]
for path in paths:
    print 'PATH:', path

print
print 'PREFIX:', os.path.commonprefix(paths)

>>> ================================ RESTART ================================
>>> 
PATH: /one/two/three
PATH: /one/two/threetxt
PATH: /one/two/three/four

PREFIX: /one/two/three

6.1.2 創建路徑
除了分解現有路徑外,還須要從其餘字符串創建路徑,使用join()。
import os.path
for parts in [ ('one', 'two', 'three'),
            ('\one', 'two', 'three'),
            ('/one', '/two', '/three', '/four'),]:

    print parts, ':', os.path.join(*parts)
若是要鏈接的某個參數以os.sep開頭,前面全部參數都會丟棄,參數會返回值的開始部分。
>>> ================================ RESTART ================================
>>> 
('one', 'two', 'three') : one\two\three
('\\one', 'two', 'three') : \one\two\three
('/one', '/two', '/three', '/four') : /four

6.1.3 規範化路徑
使用join()或利用嵌入變量由單獨的字符串組合路徑時,獲得的路徑最後可能會有多餘的分隔符或者相對路徑部分,使用normpath()能夠清除這些內容。
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構成的路徑段。
>>> ================================ RESTART ================================
>>> 
       one/two/three : one\two\three
     one/./two/three : one\two\three
one/../alt/two/three : alt\two\three
要把一個相對路徑轉換爲一個絕對文件名,能夠使用abspath()。
import os.path
for path in [ '.',
              '..',
              'one/two/three',
              'one/./two/three',
              'one/../alt/two/three',
              ]:
    print '%20s : %s' % (path, os.path.abspath(path))
結果是從一個文件系統樹最頂層開始的完整路徑。
>>> ================================ RESTART ================================
>>> 
                   . : C:\Users\Administrator\Desktop
                  .. : C:\Users\Administrator
       one/two/three : C:\Users\Administrator\Desktop\one\two\three
     one/./two/three : C:\Users\Administrator\Desktop\one\two\three
one/../alt/two/three : C:\Users\Administrator\Desktop\alt\two\three

6.1.4 文件時間
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__)
返回訪問時間,修改時間,建立時間,文件中的數據量。

6.1.5 測試文件
程序遇到一個路徑名,一般須要知道這個路徑的一些信息。
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)
全部測試都返回布爾值。
>>> ================================ RESTART ================================
>>> 
File        : C:\Users\Administrator\Desktop\tmp
Is file?     : False
Absoulute    : True
Is dir?      : True
Is link?     : False
Mountpoint?  : False
Exists?        : True
Link Exists? : True

6.1.6 遍歷一個目錄樹
import os
import os.path
import pprint
def visit(arg, dirname, names):
    print dirname, arg
    for name in names:
        subname = os.path.join(dirname, name)
        if os.path.isdir(subname):
            print '%s/' % name 
        else:
            print ' %s' % name
    print
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)')
會生成一個遞歸的目錄列表。
>>> ================================ RESTART ================================
>>> 
example (User data)
one/

example\one (User data)
 another.txt
 file.txt
相關文章
相關標籤/搜索