47 - read、readline 和 readlines 方法的区别

Noya ·
更新时间:2024-09-21
· 940 次阅读

1. 如何打开和读取文本文件内容 f = open('./files/readme.txt', 'r') print(type(f)) # print(f.read()) # f.close() 2. 使用 open函数打开文件,并返回一个 IO对象,该对象有3个用于读取文件的方法: read、readline 和 readlines。请使用代码描述这 3个方法的区别 # read: 读取文件的全部内容 print(f.read()) f.close() hello world I love you How are you? f = open('./files/readme.txt', 'r') f.read(3) # 如果指定参数n,会读取前n个字符 f.close() f = open('./files/readme.txt', 'r') f.seek(6) print(f.read(5)) f.close() world # readline # 读取一行 f = open('./files/readme.txt', 'r') print(f.readline()) print(f.readline()) f.close() hello world I love you f = open('./files/readme.txt', 'r') print(f.readline(2)) # 如果指定n,当n 比当前行字符个数小 print(f.readline(20)) # 如果超过当前行字符个数,那么最多读取当前行的内容 f.close() he llo world # readlines # 返回列表 f = open('./files/readme.txt', 'r') print(f.readlines()) f.close() ['hello world\n', 'I love you\n', 'How are you?'] f = open('./files/readme.txt', 'r') print(f.readlines(3)) # 如果指定n,只会读取行字符个数之和大于n 的行 f.close() ['hello world\n'] f = open('./files/readme.txt', 'r') print(f.readlines(12)) # 如果指定n,只会读取行字符个数之和大于n 的行 f.close() ['hello world\n', 'I love you\n']

48 - 在json 序列化时如何处理日期类型的值


作者:若尘



readlines 方法 read

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章