python中read() readline()以及readlines()对比

来源:互联网 发布:java删除sftp文件夹 编辑:程序博客网 时间:2024/05/16 08:13
该篇文章主要是记录python中操作文件的三个函数read(),readline()以及readlines()之间的区别。

首先先给出结论:

  1. .read() 每次读取整个文件,它通常将读取到底文件内容放到一个字符串变量中,也就是说 .read() 生成文件内容是一个字符串类型。
  2. .readline()每只读取文件的一行,通常也是读取到的一行内容放到一个字符串变量中,返回str类型。
  3. .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类型。

原文地址:原文地址



0 0