【Python编程:从入门到实践】第十章:文件和异常

10-2 C语言学习笔记:可使用replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的'dog'替换为'cat':

>>> message = "I really like dogs."

>>> message.replace('dog','cat')

'I really like cats.'

route = 'learning.txt'
with open(route) as file_object:
	message = file_object.read()
	print(message.rstrip())
	result = message.replace('dog','cat')
	print(result.rstrip())
结果:



10-3 访客:编写一个程序,提示用户输入器名字;用户作出响应后,将其名字写入到文件guest.txt中

if __name__ == "__main__":
    route = 'learning.txt'
    name = input('please input your name')
    with open(route,'w') as file_object:
        file_object.write(name)
    with open(route)  as  file_object:
        print(file_object.read().rstrip())
结果:



10-4 访客名单:编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。

if __name__ == "__main__":
    route = 'guest_book.txt'
    with open(route,'w') as file_object:
        while True:
            name =  input('please input your name:')
            print("Hello, ",name)
            file_object.write(name+"\n")
            conti = input("continute?yes/no")
            if conti == 'no':
                break;
    with open(route) as  file_object:
        lines = file_object.readlines()
    for line in lines:
        print(line.rstrip())
结果:
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值