我是靠谱客的博主 香蕉御姐,最近开发中收集的这篇文章主要介绍python中read() readline()以及readlines()对比,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

篇文章主要是记录python中操作文件的三个函数read(),readline()以及readlines()之间的区别。

首先先给出结论:

.read() 每次读取整个文件,它通常将读取到底文件内容放到一个字符串变量中,也就是说 .read() 生成文件内容是一个字符串类型。
.readline()每只读取文件的一行,通常也是读取到的一行内容放到一个字符串变量中,返回str类型。
.readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型。

我的文件内容如下:
在这里插入图片描述


.read()函数


编写程序如下:

# -*- coding: UTF-8 -*-
#这个代码对比一下read(),readline()和readlines()函数
file_read = open('C:/Users/m1584/Desktop/python/read_and_readline/test.txt')
print file_read.read()
print type(file_read.read())
file_read.close()

得出结果如下:
在这里插入图片描述

可以得出结论如下:

.read() 每次读取整个文件,它通常将读取到底文件内容放到一个字符串变量中,也就是说 .read() 生成文件内容是一个字符串类型

.readline()函数

编写程序如下:

# -*- coding: UTF-8 -*-
#这个代码对比一下read(),readline()和readlines()函数
file_readline = open('C:/Users/m1584/Desktop/python/read_and_readline/test.txt')
print file_readline.readline()
print type(file_readline.readline())
file_readline.close()

得出输出结果如下:
在这里插入图片描述
可以得出结论如下:
.readline()每只读取文件的一行,通常也是读取到的一行内容放到一个字符串变量中,返回str类型。

.readlines()函数

编写程序如下:

# -*- coding: UTF-8 -*-
#这个代码对比一下read(),readline()和readlines()函数
file_readlines = open('C:/Users/m1584/Desktop/python/read_and_readline/test.txt')
print file_readlines.readlines()
print type(file_readlines.readlines())
file_readlines.close()

得到输出结果如下:

在这里插入图片描述

可以得出结论如下:
.readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型。

最后

以上就是香蕉御姐为你收集整理的python中read() readline()以及readlines()对比的全部内容,希望文章能够帮你解决python中read() readline()以及readlines()对比所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(69)

评论列表共有 0 条评论

立即
投稿
返回
顶部