15:文本文件的读取

###文本文件的读取

 

文件的读取一般使用如下三个方法:

1. read([size])

从文件中读取 size 个字符,并作为结果返回。如果没有 size 参数,则读取整个文件。读取到文件末尾,会返回空字符串。

2. readline()

读取一行内容作为结果返回。读取到文件末尾,会返回空字符串。

3. readlines()

文本文件中,每一行作为一个字符串存入列表中,返回该列表

【操作】 读取一个文件前 4 个字符

with open(r"b.txt", "r", encoding='utf-8') as f:
    print(f.read(4))

输出结果:

"D:\Program Files\Python310\python.exe" D:\work\python\five\file06.py 
itba

【操作】文件较小,一次将文件内容读入到程序中

with open(r"b.txt","r") as f:
    print(f.read())

输出结果:

itbaizhan
sxt

按行读取一个文件:

with open(r"b.txt","r") as f:
    while True:
        fragment = f.readline()
        if not fragment:
            break
        else:
            print(fragment,end="")

输出结果

itbaizhan
sxt

【操作】使用迭代器(每次返回一行)读取文本文件

with open(r"d:\bb.txt","r") as f:
    for a in f:
        print(a,end="")

【操作】为文本文件每一行的末尾增加行号

with open("e.txt","r",encoding="utf-8") as f:
    lines = f.readlines()
    lines = [ line.rstrip()+" #"+str(index+1)+"\n" for index,line in enumerate(lines)] #推导式生成列表
    
with open("e.txt","w",encoding="utf-8") as f:
    f.writelines(lines)

输出结果前:

我 love u!
尚学堂
百战程序员

输出结果:

我 love u! #1
尚学堂 #2
百战程序员 #3

 

posted @ 2022-11-22 16:13  竹蜻蜓vYv  阅读(224)  评论(0编辑  收藏  举报