Python读取文件的三种方式

2019-11-12  本文已影响0人  lvyz0207

Python读取文件的三种方式

# python 文件处理
def main1():
    f = None
    try:
        f = open('致橡树.txt', 'r', encoding='utf-8')
        print(f.read())
    # except FileNotFoundError:
    #     print('无法打开指定的文件!')
    # except LookupError:
    #     print('指定了未知的编码!')
    # except UnicodeDecodeError:
    #     print('读取文件时解码错误!')
    except Exception as err:
        print("错误信息为:{}".format(err))
    finally:
        if f:
            f.close()

def main2():
    try:
        with open('致橡树.txt', 'r', encoding='utf-8') as f:
            print(f.read())
    except Exception as err:
        print("错误信息为:{}".format(err))

# 读取大文件时使用  pythonci最完美的读取文件方式,即高效又快速
def main3():
    try:
        with open('致橡树.txt', 'r', encoding='utf-8') as f:
            for line in f:
                print("---------分隔线--------")
                print(type(line))
                print(line.split()[0])
    except Exception as err:
        print("错误信息为:{}".format(err))




if __name__ == '__main__':
    # main1()
    # main2()
    main3()
上一篇下一篇

猜你喜欢

热点阅读