文本文件的读取+操作

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

1.read([size]):从文件中读取size个字符,并作为结果返回,如果没有size参数,则读取整个文件,读取到文件末尾,会返回空字符串

2.readline():读取一行内容作为结果返回,读取到文件末尾,会返回空字符串

3.readlines():文本文件中,每一行作为一个字符串存入列表中,返回该列表

操作:

# 读取一个文件前四个字符
with open(r"b.txt", 'r', encoding="GBK")as f:
    print(f.read(4))

# 文件较小,一次将文件内容读入到程序中
with open(r"b.txt", 'r', encoding="GBK")as f:
    print(f.read())
with open(r"b.txt", 'r', encoding="GBK")as f:
    print(f.readline())
with open(r"b.txt", 'r', encoding="GBK")as f:
    print(f.readlines())

# 使用迭代器(每次返回一行)读取文本文件:
with open(r"b.txt", 'r', encoding="GBK")as f:
    for line in f:
        print(line)

# 按行读取一个文件
with open(r"b.txt", 'r', encoding="GBK")as f:
    while True:
        line = f.readline()
        if not line:
            break
        else:
            print(line, end='')

# 为文本文件每一行的末尾添加行号
with open("b.txt", 'r', encoding="utf-8")as f:
    lines = f.readlines()
    lines2 = [line.rstrip() + " #" + str(index)+"\n" for index, line in zip(range(1, len(lines) + 1), lines)]
with open("b.txt", 'w', encoding="GBK")as f:
    f.writelines(lines2)