f = open(“123.txt”, “r”)
content = f.read() # read默认将读取出所有内容
print(content)
f.close()
读取大型文件的两种方式: 1> 使用read(n) 2> readline()
f = open(“123.txt”, “r”)
content = f.read(3) # read(n) 可以设置读取的字符长度
content1 = f.read(3)
print(content, end=”“)
f.close()
f = open(“123.txt”, “r”)
content = f.readline()
print(content, end=”“)
f.close()
读取大型文件 避免一次性读取的内容占用的内存过多
f = open(“123.txt”, “r”)
while True:
判断文件是否全部读完
content = f.readline()
if len(content) == 0:
break
print(content, end=”“)
f.close()
f = open(“123.txt”, “r”)
a = f.readlines() # 一次性全部读出, 每行作为一个元素,返回列表
f.close()
print(a)