python 中有关文件处理

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

猜你喜欢

转载自blog.51cto.com/13132323/2134807