python 中有關檔案處理

來源:互聯網
上載者:User

標籤:UNC   error   TE   指標   不能   ast   需要   sdn   終端   

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__inaccessibles._Secretive__inaccessible()<unbound method Secretive.__inaccessible>Bet you can‘t see me ...#檢查繼承isubclass()檢查一個對象是否為一個類的執行個體isinstance()


這裡在寫一個繼承的例子,在子類中重寫了構造方法時

#將類都變成新式類,不管是經典還是新式,都算新式類__metaclass__ =  typeclass 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.sounds =  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 = 0def __getitem__(self, index):    self.counter += 1    return super(CounterList, self).__getitem__(index)c1 = CounterList(range(10))print c1c1.reverse()print c1del c1[3:6]print c1print 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 / 0print ‘result:‘, rexcept ZeroDivisionError, e:print ‘except:‘, efinally:print ‘finally...‘print ‘END‘except 語句跟著兩個東西,前面是異常的類型,後面的是 異常對象,包含了一些異常資訊異常繼承http://blog.csdn.net/dragonfli_lee/article/details/52350793http://www.cnblogs.com/Lival/p/6203111.html
    class MyError(Exception):def __init__(self, value):    self.value = valuedef __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=10b=0try:c=a/bprint cexcept ZeroDivisionError,e:print e.messageprint "done"#處理一組異常,指的是輸入或者輸出兩組和IOError這個異常類型有關a=10b=0try:c = b/ aprint cexcept (IOError ,ZeroDivisionError),x:print xelse: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.lalafeitian.width = 1del feitian.widthfeitian.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 nestedt =  list(flatten([‘1‘,[‘bar‘,[‘baz‘]]]))print  t

python 中有關檔案處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.