读取文件

2018-08-02  本文已影响0人  话_5262

python 读取文本文件有三类方法:read()、readline()、readlines(),这三种方法各有利弊,下面介绍其使用方法和利弊。

# 格式相互转换没问题
with open('110.txt', 'r', encoding='UTF-8') as f:
    text = f.read()  # type数据类型为"str"
    print(text)

-*-*-*-*-*-*-*-*-*-*-*-华丽分割线*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

with open('110.txt', encoding='utf-8')as f:
    a = f.read()  # 读文本
    # print(a)
    with open('1101.xls', 'w', encoding='utf-8')as fx:
        fx.write(a)  # 转换格式写入Excel
        fx.close()  # 写入完成,关闭文件

-*-*-*-*-*-*-*-*-*-*-*-华丽分割线*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

with open('1101.xls', encoding='utf-8')as f:
    a = f.read()  # 读Excel文本
    # print(a)
    with open('1102.txt', 'w', encoding='utf-8')as fx:
        fx.write(a)  # 转换格式写入txt文件
        fx.close()  # 写入完成,关闭文件
with open('110.txt', 'r', encoding='UTF-8') as f:
    text = f.readline()  # 逐行读取文本,type数据类型为"str"
    while text:
        text = f.readline()
        print(text)
with open('110.txt', 'r', encoding='UTF-8') as f:
    text = f.readlines()  # type数据类型为"list"
    for i in text:
        print(i)
上一篇下一篇

猜你喜欢

热点阅读