python中逐行打印


方法一:readline函数

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


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

f = open("./code.txt")
 while True:
     lines = f.readlines(10000)
     if not lines:
         break
     for line in lines:
         print(line)
 f.close()
一次性读取多行,可以提升读取速度,但内存使用稍大, 可根据情况调整一次读取的行数


方法三:直接for循环

for line in open("./code.txt"):  
     print(line)
python3 直接将open对象加入循环体中可以那么默认一个元素就是一行

猜你喜欢

转载自www.cnblogs.com/sablier/p/10660830.html