Python读取文件常用的几种简单小操作
程序员文章站
2022-04-08 17:10:05
...
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+等
上一篇: Shell----读取文件每一行的方式
下一篇: java多线程简单的小例子