This article mainly introduces the three common methods of reading file content in Python and their efficiency comparison. It also gives three common methods of file reading in the form of specific examples and compares and analyzes the reading speed. Friends who need it can Refer to the following
The examples in this article describe three common ways for Python to read file contents. Share it with everyone for your reference, the details are as follows:
The file for this experiment is a 60M file with a total of 392660 lines of content.
Program 1:
def one(): start = time.clock() fo = open(file,'r') fc = fo.readlines() num = 0 for l in fc: tup = l.rstrip('\n').rstrip().split('\t') num = num+1 fo.close() end = time.clock() print end-start print num
Run result: 0.812143868027s
Program two:
def two(): start = time.clock() num = 0 with open(file, 'r') as f: for l in f: tup = l.rstrip('\n').rstrip().split('\t') num = num+1 end = time.clock() times = (end-start) print times print num
Running time: 0.74222778078
Program three:
def three(): start = time.clock() fo = open(file,'r') l = fo.readline() num = 0 while l: tup = l.rstrip('\n').rstrip().split('\t') l = fo.readline() num = num+1 end = time.clock() print end-start print num
Running time: 1.02316120797
It can be concluded from the results that program 2 is the fastest.
The above is the detailed content of Detailed explanation of three ways to read file content in Python and efficiency comparison. For more information, please follow other related articles on the PHP Chinese website!