[2015-08-05] python016

os.path模塊:

跟文件路徑相關

basename()      :路徑基名
dirname()       :路徑目錄名
join()
split()         :返回dirname(),basename()元組 
splitext()      :返回(filename,extension)元組

信息:

getatime()
getctime()
getmtime()
getsize()        :返回文件的大小

查詢:

exists()         :判斷指定文件是否存在
isabs()          :判斷指定的路徑是否爲絕對路徑
isdir()          :判斷指定路徑是否爲目錄
isfile()         :判斷指定路徑是否爲文件
islink()         :判斷指定路徑是否爲符號鏈接
ismount()        :判斷指定路徑是否爲掛載點
samefile()       :兩個路徑是否指向了同一個文件

練習:
判斷一個文件是否存在,存在則打開。讓用戶通過鍵盤反覆輸入多行數據,而後追加保存至此文件中

#!/usr/bin/python27
#
import os
import os.path
filename = '/tmp/test'
if os.path.isfile(filename):
    f1 = open(filename,'a+')
while True:
    line = raw_input('Enter something >')
    if line == 'q' or line == 'quit':
        break
    f1.write(line+'\n')
f1.close()

結果如圖:
結果


對象持久存儲:

pickle模塊

  • pickle.dump()
    pickle.dump()
    結果:
    結果

  • pickle.load()
    pickle.load()


其他還有一些模塊如:

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