10.2.3 附加到文件
filename = 'programming.txt'
with open(filename,'a') as f:
f.write("I also love finding meaning in large datasets.\n")
f.write("I love creating apps that can run in a browse.\n")
实参a为附加模式
#结果
I love programming.
I love creating new games.
I also love finding meaning in large datasets.
I love creating apps that can run in a browse.
课后练习
10-3编写一个程序,提示用户输入其名字;用户做出响应后,将其名字写入到文件 guest.txt
中。
filename = 'guest.txt'
name= input("Please enter your name:\n")
with open(filename,'w') as n:
n.write(name)
10-4编写一个while 循环,提示用户输入名字。用户输入名字后,在屏幕上打印一句问候语,并将一条
到访记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行
filename = 'guest_book.txt'
print("Enter 'q' to leave the game.")
while True:
name= input("\nPlease enter your name:")
print(f"Welcome come {name.title()}")
if name == 'q':
break
with open(filename,'a') as n:
n.write(f"{name.title()}\n")
编写一个while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
filename = 'reason_book.txt'
print("Enter 'q' to leave the quetion.")
while True:
reason= input("\nWhy do you like coding: ")
# print(f"Welcome come {name.title()}")
if reason == 'q':
break
with open(filename,'a') as n:
n.write(f"{reason.title()}\n")
或者如此写code
filename = 'reason_book.txt'
reasons = []
while True:
reason= input("\nWhy do you like coding: ")
reasons.append(reason)
continue_msg = input("Do you want to continue the qustions? y/n ")
with open(filename,'a') as n:
for reason in reasons:
n.write(f"{reason.title()}\n")
if continue_msg != 'y':
break