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

yipeiwu_com5年前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相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python URL操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

对django xadmin自定义菜单的实例详解

1、 自定义菜单 adminx.py class GlobalSetting(object): site_title = u'xxx后台' def kuF_site_menu...

python打开网页和暂停实例

本文实例讲述了python打开网页和暂停的方法。分享给大家供大家参考。 具体实现代码如下: import webbrowser import os webbrowser.open_...

Python实现的列表排序、反转操作示例

本文实例讲述了Python实现的列表排序、反转操作。分享给大家供大家参考,具体如下: 排序: 使用sorted方法和列表的sort方法: sorted方法适用范围更广,sort方法只有...

Python中实现的RC4算法

闲暇之时,用Python实现了一下RC4算法 编码 UTF-8 class 方式 #/usr/bin/python #coding=utf-8 import sys,os,hash...

python实现八大排序算法(2)

python实现八大排序算法(2)

本文接上一篇博客python实现的八大排序算法part1,将继续使用python实现八大排序算法中的剩余四个:快速排序、堆排序、归并排序、基数排序 5、快速排序 快速排序是通常被认为在同...