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

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

Oracle

MySQL

PostgreSQL

Redis

MongoDB

read

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

file1 = open('tb.txt', 'r')content = file1.read()file1.closeprint(content)print(type(content))输出结果:OracleMySQLPostgreSQLRedisMongoDB

readline

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

file1 = open('tb.txt', 'r')content1 = file1.readline()file1.closeprint(type(content1))print(content1)输出结果:
Oracle
from __future__ import print_functionfile1 = open('tb.txt', 'r')content = file1.readline()print(type(content))while content:  print(content, end='')  content = file1.readline()file1.close输出结果:
OracleMySQLPostgreSQLRedisMongoDB

readlines

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

file1 = open('tb.txt', 'r')content = file1.readlines()file1.closeprint(type(content))print(content)输出结果:
['Oracle\n', 'MySQL\n', 'PostgreSQL\n', 'Redis\n', 'MongoDB']

linecache.getline

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

import linecachecontent = linecache.getline('tb.txt', 4)print(type(content))print(content)输出结果:
Redis

总结

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

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

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