Python four kinds of content to read the file line by line method
The following four Python file content read line by line method to analyze the advantages and disadvantages of various methods of application scenarios, the following code in python3 tested by, python2 running part of the code annotated, slightly modified.
Method a: readline function
# -*- coding: UTF-8 -*-
f = open("/pythontab/code.txt") # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
# print line, # 在 Python 2中,后面跟 ',' 将忽略换行符
print(line, end='') # 在 Python 3中使用
line = f.readline()
f.close()
Advantages: save memory, do not need to file a one-time content into memory.
Disadvantages: relatively slow.
Method two: a multi-line data read
代码如下:
# -*- coding: UTF-8 -*-
f = open("/pythontab/code.txt")
while 1:
lines = f.readlines(10000)
if not lines:
break
for line in lines:
print(line)
f.close()
Multi-line one-time reading, can improve the reading speed, but slightly larger memory use, the first reading may be adjusted according to the number of rows where
Method three: Direct for loop
Cycle time can be used for each row of data directly to a file object, as follows:
# -*- coding: UTF-8 -*-
for line in open("/pythontab/code.txt"):
# print line, #python2 用法
print(line)
Method 4: Use fileinput module
import fileinput
for line in fileinput.input("/pythontab/code.txt"):
print(line)
Simple to use, but slower
Reprinted from: https: //www.jianshu.com/p/4658e3ed1fea