Python read() readline() readlines()
【文档目的】
讲解f=open("fpath","r")文件打开后,f.read()、f.readline()和f.readlines()返回对象的不同,及函数常见语法。
1. 输出对象
-
f.read() -> str,整个文本,包含'\n'换行符的字符串
-
f.readline() -> str,当前一行,结尾为'\n'换行符,readline会从f对象中获取当前行的读取指针
-
f.readlines() -> list,列表,所有行组成,每行为一项
2. 应用语句结构
2.1 f.read()
def f_read(fpath):
f = open(fpath,"r")
text = f.read()
for line in text.splitlines():
print(line)
f.close()
2.2 f.readline()
def f_readline(fpath):
f = open(fpath, "r")
line = f.readline()
while line:
print(line, end='')
line = f.readline()
print("\n")
f.close()
2.3 f.readlines()
def f_readlines(fpath):
f = open(fpath, "r")
lines = f.readlines()
for line in lines:
print(line, end='')
print("\n")
f.close()
测试脚本:
fpath = r"log.txt"
print("Running on f_read()")
f_read(fpath)
print("Running on f_readline()")
f_readline(fpath)
print("Running on f_readlines()")
f_readlines(fpath)