#!/usr/bin/env python3 #第一个python3程序 #书本实例3.1 import os #导入os模块 newline = os.linesep #这里定义系统的换行符 while True: filename = input("Please input a filename:") if os.path.exists(filename): #如果文件存在 print('The filename exists!Please input another filename!') else: break #如果输入的文件不存在, 那就跳出循环 filedata = [] #定义一个列表, 用于保存用户输入, 最后读取进文件中 print('Please input to %s :' % filename) while True: #当用户输入的不是#字符时, 就一直循环 userinput = input('>') if userinput != '#': filedata.append(userinput) else: break #打开文件, 把列表中的值写进去再保存 fileopen = open(filename, 'w+') fileopen.writelines(['%s%s' % (inputdata, newline) for inputdata in filedata] ) fileopen.close() print('DONE')