Python---file

import locale
import io
import gzip
import sys
class RedirectStdoutTo:
    def __init__(self, out_new):
        self.out_new = out_new

    def __enter__(self):
        self.out_old=sys.stdout
        sys.stdout=self.out_new
    
    def __exit__(self,*args):
        sys.stdout=self.out_old

'''
if one class has __enter__and __exit__, then it is context mamanger
'''

def open1(path):
    file1=open(path, encoding='utf-8')
    print(file1.read())
    print(file1.name)
    print(file1.mode)
    print(file1.encoding)
    print(file1.read())
    print(file1.tell())
    print(file1.seek(0))
    print(file1.read(1))
    print(file1.tell())
    print(file1.read())
    file1.close()
    print(file1.closed)

def open2(path):
    print('===============open2=================')
    with open(path, encoding='utf-8') as file2:
        print(file2.read())

def open3(path):
    print('==============open3======================')
    linenm=0;
    with open(path, encoding='utf-8') as file3:
        for line1 in file3:
            linenm+=1
            print('{:>4}{}'.format(linenm, line1.rstrip()))
    
def open4(path):
    print('==============open4============================')
    with open(path, mode='a', encoding='utf-8') as file4:
        '''attention, w means rewrite, r means append'''
        file4.write('add new line\n')

def open5(path):
    print('==============open5=================================')
    with open(path, mode='rb') as file5:
        '''no need pass encoding, because we're passing b--byte,binary'''
        print(file5.read(100))

def open6():
    print('=============open6=========================================')
    string1='I want to make this string as file'
    file6=io.StringIO(string1)
    print(file6.tell())
    print(file6.read())

def open7(path):
    print('===============open7=======================================')
    with gzip.open(path, mode='ab') as file7:
        file7.write('I add new line in gz file\n'.encode('utf-8'))

def open8(path):
    print('=============open8====================================')
    with open(path, mode = 'a', encoding ='utf-8') as file8, RedirectStdoutTo(file8):
        print('haha, my print is appended into files, not in console\n')
    
    with open(path, mode = 'a', encoding ='utf-8') as file8:
        with RedirectStdoutTo(file8):
            print('haha, my print is appended into file again\n')
'''
with can be without "as"
open is an context manager, because open() api return stream, 
it is context manager implemented __enter__,__exit__
RedirectStdoutTo is also context manager
'''


def getdefault():
    print(locale.getpreferredencoding())

if __name__ == '__main__':
    getdefault()
    open1('file_util_m.txt')
    open2('file_util_m.txt')
    open3('file_util_m.txt')
    open4('file_util_m.txt')
    open5('metro.jpg')
    open6()
    open7('file.gz')
    open8('file_util_m.txt')

 


posted @ 2015-12-28 20:11  xfei.zhang  阅读(214)  评论(0编辑  收藏  举报