1. 程式人生 > >python 中有關文件處理

python 中有關文件處理

subclass 也會 eas metaclass 註意 can 定位 acc instance

Python的文件處理

打開文件f = open (“path”,”mode”)

  • r 模式
    以讀的方式打開,定位到文件開頭 , 默認的 mode。文件不存在直接報錯,文件只能讀取,不能寫入。
  • r+模式
    以讀寫的方式打開,定位文件開頭 , 可以寫入內容到文件
  • w 模式
    以寫的方式打開,打開文件的時候會清空文件的內容,並且不能讀
  • w+模式
    以讀寫的方式打開,定位到文件頭,並且打開文件的時候也會清空文件的內容
  • a模式
    以寫的方式打開,定位到文件的末尾,是一個追加的操作 , 但並不允許讀
  • a+模式
    以讀寫的方式打開,定位到文件的末尾,追加的方式。

註:在使用以上 mode 打開文件的時候,如果增加了b 模式,表示以二進制方式打開

讀取文件

  • f. readline()
    其實他就是用f.next方法實現的
    f = file(“feitian.txt”,”r”)
    只獲得了文件的句柄
  • f.readline()
    一行一行的讀,每執行一次就讀取一行
  • f.read()
    以字符串的形式,一次性讀
  • f.readlines()
    是以列表的形式讀出來
    lala = file("accounts.txt","r")
    #打開文件
    for line  in lala.readlines():
    user, passwd = line.strip(‘\n‘).split()
    print user,passwd

    關閉文件

  • f.close
    關閉文件

    將內存中文件寫入文件中

    關閉文件,會將內存的內容寫入文件中(內容一般不超過1024個字符就存在內存中)

  • f.flush()
    會將內存中的文件內容寫入到文件中。

    寫入文件內容

    f =file(“feitian.txt”,’a’)
    f.write(‘\nsecond line’)
    一般不會換行,需要手動換行

    顯示文件的字符集

  • print f.encoding
    如果結果為None,就是以ascall碼的形式。
    默認是ascall如果要以其他的形式字符編碼存放,則需要用下面的語句寫入文件
    f.write(u’你是狗’.encode(‘utf-8’))

    測試是不是一個終端

    在Linux中打開一個終端其實就是創建一個tty文件

    查看name的模式

  • f.mode()
    查看file的模式
    ###查看文件的name
  • f.name()

    f.next()

    一個叠代方法,和readline差不多,不過他讀到結尾的時候會報一個錯誤

    f.seek()

    註意:這裏可以分析日誌,每次只從上次處理的地方開始分析
    f.seek(offset[,whence]),函數,offset表示移動多少字節,大於零向右偏,小於零向左偏。whence為1的時候表示相對於當前位置移動的,當是2的時候從文件的末尾往後移動,但不一定所有的平臺都支持;為0的時候表示從開頭往後移動.

    f.tell()

    找到文件的指針的位置

    f.truncate(size)

    從開頭截取到100的內容,他與文件的指針沒有關系。其他的內容都會被刪除。

    f.writelines()

    給文件中寫入多行

    f.readlines()

    讀一行打印一行
    for i in f.readlines()
    print i

    #顯示文件中所有的行,但忽略以#號開頭的行。
    f = open("world.md","a+")
    for i in f :
    i = i.strip()
    if not i.startswith("#"):
        print i 
    f.close()
    # 下面為更高級一點的代碼,在這段程序執行完畢之後自動關閉文件
    with open("world.md","a+") as f :
    for i in f :
        i = i.strip()
        if not i.startswith("#"):
            print i

註:私有方法在外部訪問
在類的內部定義中,所有以雙下劃線開始的名字都被翻譯成前面加單下劃線和類名的形式。

class Secretive(object):
    def __inaccessible(self):
        print "Bet you can‘t see me ..."
    def accessible(self):
        print "The secret message is :"
        self.__inaccessible()
s = Secretive()
print Secretive._Secretive__inaccessible
s._Secretive__inaccessible()
<unbound method Secretive.__inaccessible>
Bet you can‘t see me ...
#檢查繼承
isubclass()
檢查一個對象是否為一個類的實例
isinstance()

技術分享圖片
這裏在寫一個繼承的例子,在子類中重寫了構造方法時

#將類都變成新式類,不管是經典還是新式,都算新式類
__metaclass__ =  type
class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if  self.hungry:
            print "feitian...."
            self.hungry = False
        else:
            print "No.thinks"
class BirdSing(Bird):
    def __init__(self):
        super(BirdSing,self).__init__()
       # Bird.__init__(self)
        self.sound = ‘squawk‘
    def sing(self):
        print self.sound
s =  BirdSing()
s.sing()
s.eat()
s .eat()

基本的序列和映射規則
序列和映射是對象的集合

  • __len___(self):
  • __getitem__(self,key):
  • __setitem__(self,key,value):
  • __delitem__(slef,key):
  • __str__(self)
    把一個類的實例變成str。
    默認在找到,設置和刪除的時候會調用相應的構造方法
    子類化列表,字典和字符串

    class CounterList(list):
    def __init__(self,*args):
        super(CounterList, self).__init__(*args)
        self.counter = 0
    
    def __getitem__(self, index):
        self.counter += 1
        return super(CounterList, self).__getitem__(index)
    c1 = CounterList(range(10))
    print c1
    c1.reverse()
    print c1
    del c1[3:6]
    print c1
    print len(c1)
    c1[4]+c1[2]
    print c1.counter
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

    #有關try except異常:

    try:
    print ‘try...‘
    r = 10 / 0
    print ‘result:‘, r
    except ZeroDivisionError, e:
    print ‘except:‘, e
    finally:
    print ‘finally...‘
    print ‘END‘
    except 語句跟著兩個東西,前面是異常的類型,後面的是 異常對象,包含了一些異常信息
    異常繼承
    http://blog.csdn.net/dragonfli_lee/article/details/52350793
    http://www.cnblogs.com/Lival/p/6203111.html
    class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
    Python定義了__str__() 和__repr__()兩種方法,__str__()用於顯示給用戶,而__repr__()用於顯示給開發人員
    try:
    raise MyError(2*2)
    except MyError as e:
    print ‘My exception occurred, value:‘, e.value
    ##另一個代碼
    a=10
    b=0
    try:
    c=a/b
    print c
    except ZeroDivisionError,e:
    print e.message
    print "done"
    #處理一組異常,指的是輸入或者輸出兩組和IOError這個異常類型有關
    a=10
    b=0
    try:
    c = b/ a
    print c
    except (IOError ,ZeroDivisionError),x:
    print x
    else:
    print "no error"
    print "done"
    #有關try finally異常
    無論異常是否發生,在程序結束前,finally中的語句都會被執行。

    #Python中的有關攔截的東西

  • __getattribute__(self,name)
    #當特性name被訪問時自動被調用
  • __getattr__(self,name)
    #當name被訪問且對象沒有響應的特性時,自動被調用
  • __setattr__(self,name,value)
    #當試圖給name賦值是會被自定調用
  • __delatter__(self,name)
    #試圖刪除特性name時被調用
class Rectangle(object):
    def lala(self):
        self.width = width
    def __setattr__(self,width, value):
        print "想改,不存在的"
    def __delattr__(self, width):
        print "想刪除,也不存在"
    def __getattr__(self,lalala):
        print "你有這個屬性嗎"
    def __getattribute__(self,name):
        print "想看知道也不存在的"
feitian = Rectangle()
feitian.lala
feitian.width = 1
del feitian.width
feitian.lalala
想看知道也不存在的
想改,不存在的
想刪除,也不存在
想看知道也不存在的

Python中的遞歸生成器

def flatten(nested):
    try:
        try:nested + ‘‘
        except TypeError:pass
        else :
            raise  TypeError
        for sublist in nested:
            for element in  flatten(sublist):
                yield element
    except TypeError:
        yield nested
t =  list(flatten([‘1‘,[‘bar‘,[‘baz‘]]]))
print  t

python 中有關文件處理