写入文件
问题:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
过程:
name.py
1 filename = 'guest.txt' 2 with open(filename,'w') as file_object: 3 print ("Please enter your name:") 4 file_object.write(input())
cmd窗口下运行:python name.py 机会首先打印出
Please enter your name:,然后输入一个名字,enter结束,此时输入的名字就被写入到了guest.txt
在进一步:用户输入其名字后,在屏幕上打印一句问候语,并记录添加到文件guest_book.tx
1 filename = 'guess_book.txt' 2 with open(filename,'a') as file_object: 3 while True: 4 name = input("Please enter your name:") 5 file_object.write(name + "! Welcome come to Beijing\n") 6 if name == 'haha': 7 break