温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

read/readline/readlines的用法简介

发布时间:2020-08-06 15:08:29 来源:网络 阅读:551 作者:Darren_Chen 栏目:编程语言

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可以指定操作的行,效率也还可以;


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI