read()、readline()和readlines()三者间的区别有是读取后保存的数据类型不一样,用也有一些差别。不记清楚用着就混,比如用多了readline(),再用readlines()就会想用.replace.....
--------------下面是区别与使用解析-------------
首先打开一个文件
fi=open('路径',‘r’)
分别令
x=fi.read()
x=fi.readline()
x=fi.readlines()
分别通过Print(type(x))就可以得到三者的区别:
Print(type(x))
区别1:read()、readline()都是输出字符串
readlines输出的是列表
区别2:
read()按输入参数size=a来读取从起始位置到a的所有字符,作为字符串保存在x里面
readline()则是死板的按行读取
readlines()直接是读取文件里面全部了,转换为列表存放于x变量,每一行是列表的一个元素。
使用方法:
假设有一个文件:01.txt
用open函数打开文件:fi=open( ' 01.txt ' ,' r ' )
读取内容:
content1=fi.read()
content2=fi.readline()
content3=fi.readlines()
如果要用read来读取全文,不设置size就可以了,默认读取到结尾
如果用readline来读取全文,就要用for循环或者while循环
如:
#-*- coding:utf-8 -*-
fi=open('C:/Users/nansbas/Desktop/01.txt','r')
while True:
line=fi.readline()
if line:
print(line)
else:
break
结果如下:
或者用for循环
#-*- coding:utf-8 -*-
fi=open('C:/Users/nansbas/Desktop/01.txt','r')
for line in fi:
if line:
print(line)
else:
break
结果如下: