注:在使用以上 mode 打開文件的時候,若是增長了b 模式,表示以二進制方式打開html
lala = file("accounts.txt","r") #打開文件 for line in lala.readlines(): user, passwd = line.strip('\n').split() print user,passwd
f.close
關閉文件ide
關閉文件,會將內存的內容寫入文件中(內容通常不超過1024個字符就存在內存中)函數
f =file(「feitian.txt」,’a’)
f.write(‘\nsecond line’)
通常不會換行,須要手動換行測試
在Linux中打開一個終端其實就是建立一個tty文件編碼
一個迭代方法,和readline差很少,不過他讀到結尾的時候會報一個錯誤.net
注意:這裏能夠分析日誌,每次只從上次處理的地方開始分析
f.seek(offset[,whence]),函數,offset表示移動多少字節,大於零向右偏,小於零向左偏。whence爲1的時候表示相對於當前位置移動的,當是2的時候從文件的末尾日後移動,但不必定全部的平臺都支持;爲0的時候表示從開頭日後移動.翻譯
找到文件的指針的位置指針
從開頭截取到100的內容,他與文件的指針沒有關係。其餘的內容都會被刪除。日誌
給文件中寫入多行code
讀一行打印一行
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()
基本的序列和映射規則
序列和映射是對象的集合
__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中的有關攔截的東西
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 想看知道也不存在的 想改,不存在的 想刪除,也不存在 想看知道也不存在的
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