Home > Backend Development > Python Tutorial > Detailed explanation of three ways to read file content in Python and efficiency comparison

Detailed explanation of three ways to read file content in Python and efficiency comparison

黄舟
Release: 2017-10-09 10:30:28
Original
2139 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template