《Python编程:从入门到实践》第10章-文件和异常 习题

10-1 Python学习笔记

在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can” 打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with代码块打印它们。

(1)打印时读取整个文件

file_name = "py_learning.txt"

with open(file_name) as file_object:
	lines = file_object.read()
	print(lines.rstrip())	

小结:

  • 方法read()读取文件的全部内容。
  • 方法rstrip()删除末尾的空格。
  • 方法strip()删除两端的空格。

△(2)打印时遍历文件对象。

file_name = "learning_python.txt"

with open(file_name) as file_object:
	for line in file_object:
		print(line.strip())

展示一种错误写法
在写这段的时候写成:

lines = file_object.read()
for line in lines:
	print(line.strip())

要多加注意。

(3)将各行存储在一个列表中,再在with代码块外打印它们

file_name = "learning_python.txt"

with open(file_name) as file_object:
	lines = file_object.readlines()

for line in lines:
	print(line.strip())

上述输出结果均为:

In Python you can establish dictionary.
In Python you can establish list.
In Python you can use while, for and if to do logical judgment.
In Python you can use function to solve problems.

10-2 C语言学习笔记

可用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的‘dog’替换为‘cat’:

>>> message = "I really like dogs."
>>> message.replace('dog', 'cat')
'I really like cats.'

读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。

file_name = "learning_python.txt"

with open(file_name) as file_objects:
	contents = file_objects.read()
	contents_change = contents.replace('Python', 'C')
	print(contents_change)

build

In C you can establish dictionary.
In C you can establish list.
In C you can use while, for and if to do logical judgment.
In C you can use function to solve problems.

10-3 访客

编写一个程序,提示用户输入其名字。用户作出响应后,将其名字写入到文件guest.txt中。

filename = "guest.txt"

username = input("Please input your name:")

with open(filename, 'w') as file_object:
	file_object.write(username)

Tools—SublimeREPL—Python—Python-runcurrentfile

Please input your name:

输入 “Yan Junze”

Please input your name:Yan Junze

***Repl Closed***

打开与该Python程序同一个文件夹的guest.txt
在这里插入图片描述
该字符串被写入文件。

10-4 访客名单

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

filename = "guest_book.txt"

print("Enter 'quit' when you are finished.\n")

active = True
while active:
	username = input("What's your name? "
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值