欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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+等

相关标签: Python 读文件