10-1 Python学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至此学习到的python知识,其中每一行都以“In Python you can”打头。将这和文件命名为learning_python.txt,并将其存储到为完成本章节练习而编写的程序所在的目录。编写一个程序,它读取这个文件,并将所写内容打印三遍:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行内容存储到一个列表中,再在with代码块外打印它们。
with open('learning_python.txt') as file_object: contents = file_object.read() print(contents.rstrip()) 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() string = '' for line in lines: string = string + line.strip() print(string)
10-2 C语言学习笔记:可使用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的“dog”替换为“cat”:
message = "I really like doges." print(message.replace('dog', 'cat'))
读取刚创建的文件learning_python.txt中的每一行,将其中Python都替换为另一门语言,如C。将修改后的各行都打印到屏幕上。
with open('learning_python.txt') as file_object: for line in file_object: line = line.replace('Python', 'C') print(line.rstrip())
10-3 访客:编写一个程序,提示用户输入其名字;用户做出响应后,将其名字写入到文件guest.txt中。
filename = 'guest.txt' with open(filename, 'w') as file_object: name = input('Please enter your name: ') file_object.write(name)
10-4 访客名单:编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest.txt中。确保这个文件中的每条记录都独占一行。
filename = 'guest.txt' with open(filename, 'w') as file_object: while True: name = input("Please enter your name and enter 'q' to quit: ") if name == 'q': break else: great_user = "Hello " + name + ".\n" print(great_user) file_object.write(great_user)
10-5 关于编程的用户调查:编写一个while循环,询问用户为何喜欢编写。每当用户输入一个原因后,都将添加到一个存储所有原因的文件中。
filename = 'The reason of like programming.txt' with open(filename, 'w') as file_object: file_object.write("The reason of our like programming:\n") with open(filename, 'a') as file_object: while True: reason = input("Enter the reason of you like programming and if enter 'q' to quit: ") if reason == 'q': break else: file_object.write(reason + '\n')