第八次作业(第十章)

本文介绍了使用Python进行文件读写的基本方法,包括读取文件内容、逐行读取文件、读取文件到列表,以及将数据写入文件。此外,还展示了如何处理输入异常,确保程序稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10-1

with open('learning_python.txt') as file_object:
	contents=file_object.read()
	print(contents)

with open('learning_python.txt') as file_object:    
	for line in file_object:
		print(line.rstrip())
with open('learning_python.txt') as file_object:
	lines=file_object.readlines()
for line in lines:
	print(line.rstrip())


10-3

filename="guest.txt"
with open(filename,'w') as file_object:
	for i in range(0,3):
		file_object.write(input("Please input the guest's name:")+'\n')  


10-6

def add():
	one=input("Please input the first number:")
	two=input("Please input the second number:")
	try:
		int(one)
		int(two)
	except ValueError:
		print("you should input numbers that don't contain characters.")
	else:
		sum=int(one)+int(two)
		print(str(sum))
add()
add()

10-11

import json
filename="fav.json"
try:
	with open(filename) as f_obj:
		number=json.load(f_obj)
		print("I know your favorite number is "+str(number))
except FileNotFoundError:
	with open(filename,'w') as f_obj:
		num=input("Please input the number that you like:")
		json.dump(num,f_obj)


10-12

import json
filename="favorite_num.json"

def store():
	with open(filename,'w') as f_obj:
		num=input("Please input your favorite number:")
		json.dump(num,f_obj)

def read():
	try:
		with open(filename) as f_obj:
			number=json.load(f_obj)
			print("I know your favorite number! It's "+number)
	except FileNotFoundError:
		store()

read()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值