python的readline()和readlines()

readlines() 是 Python 中用于从文件对象中读取所有行的方法。它会一次性读取整个文件内容,并将每一行作为一个字符串存储在一个列表中返回。

使用方法和返回值

  • 使用 readlines() 方法可以读取文件的所有内容,每一行作为列表中的一个元素。
  • 如果文件很大,一次性读取可能会占用较多内存,因此在处理大文件时需要注意内存消耗。

示例说明

假设有一个文本文件 example.txt 包含以下内容:


 
 
  1. Hello Python!
  2. This is a test file.
  3. Goodjob!

可以通过以下代码使用 readlines() 方法读取文件的所有行:


 
 
  1. file_path = 'example.txt'
  2. with open(file_path, 'r') as file:
  3. lines = file.readlines()
  4. for line in lines:
  5. print(line.strip()) # 使用 strip() 方法去除每行末尾的换行符

运行这段代码后,将会输出文件的每一行内容:


 
 
  1. Hello Python!
  2. This is a test file.
  3. Goodjob!

注意事项
  • 返回的列表中每个元素是一个字符串,包含文件中相应行的内容。
  • 每行末尾的换行符 \n 会被保留在字符串中,如果需要可以使用字符串的 strip() 方法去除。

readlines() 是在需要一次性读取整个文件内容,并且希望将每一行分别处理时非常有用的方法。

readline()

readline() 是 Python 中用于从文件对象中读取单行内容的方法。它按行读取文件,每次调用 readline() 会读取文件的下一行。

readline() 的使用方法

基本语法
line = file.readline(size=-1)

 
 

  • size(可选):指定要读取的字节数。默认是 -1,表示读取整行内容,包括行末的换行符。如果提供一个正整数,则会读取指定字节数的内容,直到遇到换行符或到达字节限制。
返回值
  • 返回的内容:读取到的内容是字符串形式的一行(包括行末的换行符)。如果到达文件末尾,则返回一个空字符串 ''
  • 返回值示例
    
       
       
    1. # 读取到的行
    2. line = "This is a line of text.\n"
示例代码

假设有一个文件 example.txt,内容如下:


 
 
  1. Line 1
  2. Line 2
  3. Line 3

以下是使用 readline() 方法读取文件内容的代码示例:


 
 
  1. # 打开文件
  2. with open( 'example.txt', 'r') as file:
  3. # 读取第一行
  4. line1 = file.readline()
  5. print(line1, end= '') # 输出 "Line 1"
  6. # 读取第二行
  7. line2 = file.readline()
  8. print(line2, end= '') # 输出 "Line 2"
  9. # 读取第三行
  10. line3 = file.readline()
  11. print(line3, end= '') # 输出 "Line 3"

在这个示例中,readline() 方法每次读取文件的下一行,直到文件结束。

readline() 的高级用法
  1. 指定读取字节数

    可以使用 size 参数指定要读取的字节数,直到遇到换行符或到达字节限制:

    
       
       
    1. with open( 'example.txt', 'r') as file:
    2. line = file.readline( 5) # 读取 5个字节
    3. print( line) # 可能输出 "Line\n"
  2. 读取文件的特定行

    结合 readline() 和循环,可以读取文件中的特定行:

    
       
       
    1. with open( 'example.txt', 'r') as file:
    2. for i in range( 2): # 读取前两行
    3. line = file.readline()
    4. print( line, end = '')
  3. 读取多行内容

    通过循环调用 readline() 方法,可以逐行读取文件内容:

    
       
       
    1. with open( 'example.txt', 'r') as file:
    2. while True:
    3. line = file.readline()
    4. if not line:
    5. break
    6. print( line, end = '')
readline() 与 readlines() 的比较
方法功能返回值类型使用场景
readline()读取单行内容单行字符串逐行读取文件内容
readlines()读取文件所有行列表(每行是一个字符串)一次性读取整个文件内容
readline() 的常见应用场景
  1. 处理大文件
    逐行读取大文件时比 readlines() 更节省内存,因为它不将整个文件内容加载到内存中。

  2. 文件处理任务
    用于按需读取文件的每一行进行处理,比如日志分析、逐行查找特定内容等任务。

示例代码汇总

以下是一些 readline() 的使用示例:


 
 
  1. # 打开文件并读取第一行
  2. with open( 'example.txt', 'r') as file:
  3. first_ line = file.readline()
  4. print(f "First line: {first_line.strip()}")
  5. # 读取每一行并处理
  6. with open( 'example.txt', 'r') as file:
  7. while True:
  8. line = file.readline()
  9. if not line:
  10. break
  11. print(f "Processing line: {line.strip()}")
  12. # 使用 readline( size) 读取指定字节数
  13. with open( 'example.txt', 'r') as file:
  14. part_ of_ line = file.readline( 4)
  15. print(f "First 4 bytes of the first line: {part_of_line}")

这些示例展示了如何使用 readline() 读取文件的单行内容、逐行处理文件以及按字节数读取部分内容。

需要注意:

执行完后的指针位置

当每一次执行完readline() ,文件的指针都位于下一行的开头。而执行完readlines()后,文件的指针位于文件末尾。下面这段代码可以看出而执行完readlines()后的指针位置正是位于文件的尾部。


 
 
  1. with open( 'demo.csv', 'r', encoding= 'gbk') as f:
  2. f.seek( 0, 2) # 将指针移至文件尾
  3. print(f.tell()) # 获得文件尾的指针,执行结果238
  4. f.seek( 0) # # 将指针移至文件头
  5. lines = f.readlines()
  6. print(f.tell()) # 执行结果238

 两种方法都是从指定的文件指针作为起点开始读取


 
 
  1. with open( 'demo.csv', 'r', encoding= 'gbk') as f:
  2. f.seek( 20) # 将指针移至文件头的20字节
  3. lines = f.readlines() # 从指针处开始读取
  4. print(lines)

或:


 
 
  1. with open( 'demo.csv', 'r', encoding= 'gbk') as f:
  2. f.seek( 20) # 将指针移至文件头的20字节
  3. line = f.readline() # 从指针处开始读取
  4. print(line)

 但是如果有汉字字符,需注意不要将汉字的字节拆开,否则会报错。

使用文件指针读取文件最后的几行 

当文件很大,比如是某个运行日志,每次只需要读取最后的几行,就可以采用:


 
 
  1. def tail( file_path, num_lines):
  2. with open(file_path, 'r', encoding= 'gbk') as f:
  3. # 将文件指针移到文件末尾
  4. f.seek( 0, 2)
  5. # 获取文件末尾位置
  6. end_pos = f.tell()
  7. lines = []
  8. line_count = 0
  9. # 逐行向前读取文件内容,直到达到指定的行数或文件开头
  10. for pos in range(end_pos - 1, - 1, - 2):
  11. f.seek(pos)
  12. next_char = f.read( 1)
  13. if next_char == '\n':
  14. # lines.append(f.readline().rstrip('\n')) 用readline()的方法
  15. line_count += 1
  16. # f.seek(pos-1)
  17. if line_count == num_lines:
  18. lines = f.readlines() # 用readlines()的方法
  19. break
  20. # 返回结果,注意如果用readline()的方法要逆序输出
  21. return lines
  22. # return lines[::-1] # 逆序输出
  23. # 调用函数并显示最后5行内容
  24. file_path = 'demo.csv'
  25. num_lines = 5
  26. last_lines = tail(file_path, num_lines)
  27. for line in last_lines:
  28. print(line.rstrip( '\n'))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值