亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

精通 Python readline():高效逐行读取文件

精通 Python readline():高效逐行读取文件

什么是 Python readline()?

readline() 是内置文件方法,从文件对象返回下一完整行。返回字符串以换行符(\n)结尾。到达文件末尾返回空字符串。

可选传 size 参数限制读取字节数。负值或省略则返回整行。

关键特性

语法

file_object.readline([size])

参数

返回值

包含下一行的字符串(或 bytes),文件耗尽时返回空字符串。

示例 1:读取首行

假设 demo.txt 包含:

Testing - FirstLine
Testing - SecondLine
Testing - Third Line
Testing - Fourth Line
Testing - Fifth Line

Python 代码:

with open("demo.txt", "r") as f:
    first_line = f.readline()
    print(first_line)

输出:

Testing - FirstLine

示例 2:使用 size 参数

仅读首行前 10 字符:

with open("demo.txt", "r") as f:
    partial = f.readline(10)
    print(partial)

输出:

Testing -

Python 基础文件 I/O

open(path, mode) 打开文件。常用模式:

模式描述
r读取(默认)
w写入(截断)
a追加
rb二进制读取
wb二进制写入

逐行读取文件

用 while 循环配合 readline():

with open("demo.txt", "r") as f:
    line = f.readline()
    while line:
        print(line)
        line = f.readline()

用 for 循环(可读性更佳):

with open("demo.txt", "r") as f:
    for line in f:
        print(line)

一次性读取所有行

Python readlines() 返回所有行列表:

with open("test.txt", "r") as f:
    lines = f.readlines()
    print(lines)

示例输出:

["Line No 1\n", "Line No 2\n", "Line No 3\n", "Line No 4\n", "Line No 5"]

总结

Python

  1. Python print() 函数完全指南:基础用法、空行打印与自定义结束符
  2. Python str.count() 完全指南:统计字符与子串出现次数实战
  3. Python format() 字符串格式化完全指南:占位符、格式化规范、类与字典应用
  4. Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
  5. 精通 Python Lambda 函数:实用示例与最佳实践
  6. Python round() 函数详解与实战示例
  7. 精通 Python map() 函数:语法、示例与最佳实践
  8. Python timeit():精准测量代码执行时间与实战示例
  9. Python collections.Counter:高效计数、更新与算术运算
  10. 理解 Python type() 与 isinstance():实战示例详解
  11. 精通 Java String.indexOf():定位子字符串与实战示例
  12. 精通 Java String compareTo():语法、用例与实战示例