第五周作业b 第10章选做(1、2、4、8)

本文介绍了Python中文件操作的基本方法,包括读取文件的不同方式及如何处理文件读取过程中可能出现的异常情况。文中还展示了如何使用seek()方法控制文件读取的位置,并通过实际代码示例演示了如何替换文件中的特定字符串。
10.1
with open("learning_python.txt")as fob:
	print("print_1:")
	data=fob.read()
	print(data)
	
	print("print_2:")
	fob.seek(0,0)
	for line in fob:
		print(line.strip())
	
	print("print_3:")
	fob.seek(0,0)
	lines=fob.readlines()
	for line in lines:
		print(line.strip())

PS:注意文件指针,使用方法tell()和seek()


10.2

with open("learning_python.txt")as fob:
	fob.seek(0,0)
	lines=fob.readlines()
	for message in lines:
		print(message.replace("Python","C"))

10.4

#coding=gbk
while True:
	name=input("请输入用户名,退出则输入0:")
	if(name=="0"):
		break
	with open("name.txt","a") as fob:
		fob.write(name)
		print("欢迎登陆!"+name)


10.8

def showfile(filename):
	try:
		with open(filename) as f:
			message=f.read()
	except FileNotFoundError:
		msg="The file "+filename+" is not exsit!"
		print(msg)
	else:
		print("The file shows:")
		print(message)

if __name__ == '__main__':
	showfile("cat.txt")
	showfile("hehe.txt")
	showfile("dog.txt")
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值