脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python按行读取文件的实现方法【小文件和大文件读取】

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

2020-09-08 10:04RQSLT Python

这篇文章主要介绍了Python按行读取文件的实现方法,结合实例形式分析了针对小文件和大文件的读取方法,需要的朋友可以参考下

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

小文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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)

大文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
#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程序设计有所帮助。

延伸 · 阅读

精彩推荐