10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt 中。
编写Python代码:
username = input("Please enter your name: ")
filename = 'guest.txt' with open(filename, 'w') as name:
name.write(username)
10-4 访客名单:编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt 中。确保这个文件中的每条记录都独占一行。
filename = 'guest_book.txt'
print("Enter 'q' when you are finished. ") while True:
username = input("What's your name? ")
if username == 'q':
break
else:
with open(filename, 'a') as name:
name.write(username + "\n")
print("Hi " + username + ",you've been added to the guest book." )
10-5 关于编程的调查:编写一个while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
filename='programming_poll.txt'
responses = []
while True:
response = input("\nWhy do you like programming? ")
responses.append(response) continue_poll = input("Would you like to let someone else respond? (y/n)")
if continue_poll == 'n':
break with open(filename, 'a') as f:
for response in responses:
f.write(response + '\n')
调用open()方法时,需要提供两个实参:文件名(file)和模式(mode)
'w'表示写入模式,若要写入的文件不存在,则会自动创建,若要写入的文件已经存在,Python在返回文件对象之前会清空该文件。
'r'表示只读模式,若不传递mode参数,默认会以只读'r'打开文件
'a'表示附加模式,若要操作的文件不存在,则会自动创建,若文件已经存在,则会在末尾追加要写入的内容。