Home  >  Article  >  Backend Development  >  How to implement Python to read files line by line [Small file and large file reading]

How to implement Python to read files line by line [Small file and large file reading]

高洛峰
高洛峰Original
2017-02-22 16:10:151717browse

The example in this article describes the implementation method of reading files line by line in Python. Share it with everyone for your reference, the details are as follows:

Small file:

#coding=utf-8
#author: walker
#date: 2013-12-30
#function: 按行读取小文件
all_lines = []
try:
  file = open('txt.txt', 'r')
  all_lines = file.readlines()
except IOError as err:
  print('File error: ' + str(err))
finally:
  if 'file' in locals():
    file.close()
for line in all_lines:
  print(line)

Large file:

#coding=utf-8
#author: walker
#date: 2013-12-30
#function: 按行读取大文件
try:
  file = open('txt.txt', 'r')
  for line in file:
    print(line)
except IOError as err:
  print('File error: ' + str(err))
finally:
  if 'file' in locals():
    file.close()


For more implementation methods of reading files line by line in Python [Small file and large file reading], please pay attention to the PHP Chinese website for related articles!

Statement:
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