python中有三种读取文件的函数:
- read()
- readline()
- readlines()
然而它们的区别是什么呢,在平时用到时总会遇到,今天总结一下。
0. 前期工作
首先新建一个文件read.txt,用于实际效果举例
Hello
welcome to my world
you are so clever !!!
1. read()
测试程序如下:
import os
with open(os.path.join(os.getcwd(), 'read.txt')) as f:
content = f.read()
print(content)
print(type(content))
这里需要注意两点:
我用到了os相关操作,即省去了需要输入文件完整路径的麻烦。
大家要养成with open file as f: 这一习惯,即操作完毕后让其自动关闭文件。
Hello
welcome to my world
you are so clever !!!
<class 'str'>
Process finished with exit code 0