方法一:readline函数

f = open("./code.txt")  # 返回一个文件对象  
line = f.readline()  # 调用文件的 readline()方法  
while line:  
     print(line, end = '')  # 在 Python 3中使用
     line = f.readline()
 f.close()

 

方法二:一次读取多行数据

 with open ("./code.txt","r") as f :
     lines = f.readlines(10000)
     for line in lines:
         print(line)

一次性读取多行,可以提升读取速度,但内存使用稍大, 可根据情况调整一次读取的行数

 

方法三:直接for循环

for line in open("./code.txt"):  
     print(line)

python3 直接将open对象加入循环体中可以那么默认一个元素就是一行

相关文章:

  • 2021-07-31
  • 2021-03-31
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-25
  • 2022-12-23
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
  • 2021-10-07
  • 2021-10-18
相关资源
相似解决方案