网络编程
位置:首页>> 网络编程>> Python编程>> Python按行读取文件的实现方法【小文件和大文件读取】

Python按行读取文件的实现方法【小文件和大文件读取】

作者:RQSLT  发布时间:2021-12-11 01:31:08 

标签:Python,读取文件

本文实例讲述了Python按行读取文件的实现方法。分享给大家供大家参考,具体如下:

小文件:


#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)

大文件:


#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()

希望本文所述对大家Python程序设计有所帮助。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com