玖叶教程网

前端编程开发入门

3分钟掌握Python 中 read、readline 和 readlines 的区别

Python 中有三个主要的函数可以用来从文件中读取内容:read()、readline() 和 readlines()。它们的区别如下:

  • read() 函数可以一次性读取整个文件,并返回一个字符串。如果不提供参数,它会读取整个文件。如果提供一个参数 n,它会读取最多 n 个字节的内容。
  • readline() 函数可以从文件中读取一行,并返回一个字符串。如果不提供参数,它会读取整行。如果提供一个参数 n,它会读取最多 n 个字符的内容,但是如果行长超过 n,则只返回前 n 个字符。
  • readlines() 函数可以从文件中读取所有的行,并返回一个列表。如果不提供参数,它会读取所有的行。如果提供一个参数 n,它会读取最多 n 个字符的内容,并且将其作为列表元素。

下面是一些简单的例子来说明这三个函数的用法:

  • 如果想要检查一个字符串是否在文件中,可以使用 read() 函数来读取整个文件,并使用 in 运算符来判断字符串是否在返回的文本中。
string = "word"
in_file = False

with open("example.txt", "r") as f:
    if string in f.read():
        in_file = True
        print(in_file)
#Output: True
  • 如果想要逐行处理文件中的内容,或者从文件中提取某些特定的行,可以使用 readline() 或 readlines() 函数来分别处理每一行或每一行列表。
with open("example.txt") as f:
    lines = f.readlines()
    for line in lines:
        print(line)
#Output:
#This is the first line
#This is the second line
#This is the third line

with open("example.txt") as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        if i % 2 == 0:
            print(line)
#Output:
#This is the first line
#This is the third line
  • 如果想要获取文件中最后 N 行或前 N 行,可以使用 readlines() 函数来获取所有行列表,并使用切片操作符来获取指定范围内的元素。
n = 5

with open("example.txt") as f:
    last_n_lines = f.readlines()[-n:]
    print(last_n_lines)
#Output:
['This is the fifth line', 'This is the sixth line']

with open("example.txt") as f:
    first_n_lines = f.readlines()[n:]
    print(first_n_lines)
#Output:
['This is the first line', 'This is the second line', 'This is the third line']

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言