Home > Article > Backend Development > How to implement Python to read files line by line [Small file and large file reading]
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!