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

高洛峰
Release: 2017-02-22 16:10:15
Original
1708 people have browsed it

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

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


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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!