注:在使用以上 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