1. 普通读取f = open()
# 打开文件,循环读取
def read(filename):
f = open(filename, 'r')
for line in f:
print(line)
2. with上下文读取
def read(filename):
with open(filename, 'r') as f:
for line in f:
print(line)
3. readline()读取,通过 while循环+not 判断是否读完
def read(filename):
with open(filename, 'r') as f:
while True:
line = f.readline()
if not line:
break
else:
print(line)
4. readlines()读取
def read(filename):
with open(filename, 'r') as f:
lines:list = f.readlines() # 得到由每一行内容构成的list
print(lines)
5. 使用生成式
def read(filename):
with open(filename, 'r') as f:
items = [item for item in f.readlines()] # 使用生成式
for item in items:
print(item)
open函数的读取mode常用参数有:r,rb(以二进制形式读取),r+等