import syswith open("stream/test.txt") as f1:sys.stdout.write(f1.read()) # 默认情况下,read() 将读取字符,直至到达文件末尾sys.stdout.write(f1.read()) # 再次读取,将返回空字符串print("---------------------")with open("stream/test.txt", "r+") as f1:# read 的参数 size 是个整数,表示最多读取多少个字符sys.stdout.write(f1.read(3) + "\n")sys.stdout.write(f1.read()) # 读取剩下的字符print("---------------------")with open("stream/test.txt", "r+") as f1:# readline() 只读取到换行符(\n),而不是读到文件末尾sys.stdout.write(f1.readline())sys.stdout.write(f1.readline())print("---------------------")with open("stream/test.txt", "r+") as f1:# 一次性将文件的所有行读取为字符串列表lines = f1.readlines()for line in lines:sys.stdout.write(line)print("---------------------")with open("stream/test.txt", "r+") as f1:# readlines 的参数 hint 是个整数,限制读取的字符数量# 读取 hint 个字符后,会继续读取直到遇到换行符lines = f1.readlines(3)for line in lines:sys.stdout.write(line)print("---------------------")with open("stream/test.txt", "r+") as f1:# 流本身就是一个迭代器# 直接迭代流比先读取所有行再迭代更快,因为不需要在内存中保存所有行for line in f1:sys.stdout.write(line)print("---------------------")with open("stream/test.txt", "r+") as f1:f1.read(3)# tell()方法返回一个整数,表示从文件开头到当前流位置的字符数print(f1.tell()) # 3# seek() 方法用于移动文件读取指针# seek(0) 会将文件指针移动到文件开头f1.seek(0)print(f1.tell()) # 0sys.stdout.write(f1.readline())f1.seek(0, 2) # 移动到文件末尾print(f1.tell()) # 12
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。