python读写文件中read()、readline()和readlines()的用法,,python中有三种


python中有三种读取文件的函数:

read()readline()readlines()

然而它们的区别是什么呢,在平时用到时总会遇到,今天总结一下。

0. 前期工作

首先新建一个文件read.txt,用于实际效果举例

Hellowelcome to my worldyou are so clever !!!

1. read()

read(size)方法从文件当前位置起读取size个字节,默认(无参数)表示读取至文件结束为止,它的返回为字符串对象

测试程序如下:

import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f:    content = f.read()    print(content)    print(type(content))

这里需要注意两点:

我用到了os相关操作,即省去了需要输入文件完整路径的麻烦。

大家要养成with open file as f: 这一习惯,即操作完毕后让其自动关闭文件。

Hellowelcome to my worldyou are so clever !!!<class ‘str‘>Process finished with exit code 0

2. readline()

每次只读一行内容,读取时内存占用较少(适用于大文件),它的返回为字符串对象

测试程序:

import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f:    content = f.readline()    print(content)    print(type(content))

输出结果:

Hello<class ‘str‘>Process finished with exit code 0

3. readlines()

读取文件所有行,保存在列表(list)变量中,列表中每一行为一个元素,它返回的是一个列表对象。

测试程序:

import oswith open(os.path.join(os.getcwd(), ‘read.txt‘)) as f:    content = f.readlines()    print(content)    print(type(content))

输出结果:

[‘Hello\n‘, ‘welcome to my world\n‘, ‘1234\n‘, ‘you are so clever !!!‘]<class ‘list‘>Process finished with exit code 0

python读写文件中read()、readline()和readlines()的用法

评论关闭