10-1: Python学习笔记
在文本编辑器中新建一个文件,写几句话来总结一下你至此学习到的Python知识,
其中每一行都以“In Python you can" 打头。 将这个文件命名为learning_python.txt,
并存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,
并将你所写的内容打印三次:第一次打印的时候读取整个数据,第二次打印的时候遍历文件对象,
第三次打印的时候将各行存储在一个列表中,再在‘with’代码块外使用他们。
filename = 'learning_python.txt'
with open(filename) as file_object:
contents = file_object.read()
print(contents)
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
with open(filename) as file_object:
lines = file_object.readlines()
leaning_string = ''
for line in lines:
leaning_string += line
print('\n' + leaning_string)
输出结果:
In Python you can read key date!
In Python you can loop through data!
In Python you can calculate numbers!
In Python you can read key date!
In Python you can loop through data!
In Python you can calculate numbers!
In Python you can read key date!
In Python you can loop through data!
In Python you can calculate numbers!
练习10-2:C语言学习笔记
可使用方法replace()将字符串中特定的单词都替换为另一个单词。下面是一个简单的示例,
演示了如何将句子中的“dog“替换成”cat”:
>>> message = "I really like dogs."
>>> message.replace("dog", "cat")
"I really like cats."
读取你刚刚创建的文件learning_python.txt中的每一行,
将其中的Python都替换为另一门语言的名称,比如C。将修改后的各行都打印到屏幕上。
filename = 'learning_python.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
new_line = line.replace('Python', 'C')
print(new_line.rstrip())
输出结果:
In C you can read key date!
In C you can loop through data!
In C you can calculate numbers!
练习 10-3: 访客
编写一个程序,提示用户输入名字。用户做出响应后,将其名字写入文件guest.txt中。
# write_guest.py
filename = 'guest.txt'
enter = input("Enter your name: ")
with open(filename, 'w') as file_object:
file_object.write(f"Username: {enter.title()}")
输出文件:
#