python中读取文件的三种方法read(),readline(),readlines()


测试文件tb.txt文件的内容:

Oracle

MySQL

PostgreSQL

Redis

MongoDB


read

返回的是字符串类型,默认读取文件的全部内容;

file1 = open('tb.txt', 'r')
content = file1.read()
file1.close

print(content)
print(type(content))

输出结果:
Oracle
MySQL
PostgreSQL
Redis
MongoDB
<type 'str'>

readline

返回的是字符串类型,默认每次只加载读取一行;

file1 = open('tb.txt', 'r')
content1 = file1.readline()
file1.close

print(type(content1))
print(content1)

输出结果:
<type 'str'>
Oracle

from __future__ import print_function


file1 = open('tb.txt', 'r')
content = file1.readline()

print(type(content))
while content:
  print(content, end='')
  content = file1.readline()
file1.close

输出结果:
<type 'str'>
Oracle
MySQL
PostgreSQL
Redis
MongoDB

readlines

返回的是list类型,默认返回的是文件中全部内容;

file1 = open('tb.txt', 'r')
content = file1.readlines()
file1.close
print(type(content))
print(content)

输出结果:
<type 'list'>
['Oracle\n', 'MySQL\n', 'PostgreSQL\n', 'Redis\n', 'MongoDB']

linecache.getline

返回的是list类型,指定返回某一行;

import linecache
content = linecache.getline('tb.txt', 4)

print(type(content))
print(content)

输出结果:
<type 'str'>
Redis


总结

read和readlines需要把整个大文件加载到内存中,所以操作大文件比较慢;

而readline是每次只加载一行,占用内存小,所以操作大文件的时候比较快;

linecache.getline可以指定操作的行,效率也还可以;