#/usr/bin/env python#模块文档"in order to create a file "#引入模块import os
#给出当前平台的行终止符
ls = os.linesep
#判断文件是否存在+whileTrue:
fname = input("please input the name of the file:")
if os.path.exists(fname):
print ("Error:'%s' already exists" % fname)
continueelse:
break#创建一个新文件
all = []
#提示语:当输入.时即结束输入print ("Enter line ('.' by itself to quit).\n")
#loop until user terminate inputwhileTrue:
entry = input(">")
if entry == ".":
breakelse:
all.append(entry)
#将输入写入文件中#以可写的方式打开创建的文件
fobj = open(fname,'w')
for x in all:
#wirtelinees()方法的作用是将可迭代对象(这里是个列表)写入文件中,如下的作用:一次循环输入列表中的一个对象和一个当前的行终止符
fobj.writelines(['%s%s' % (x,ls)])
fobj.close()
print ('DONE!')
判断一个文件是否存在,若存在则按行输出文件内容到屏幕上
#/usr/bin/env python"open a file"#get a file name
fname = input("Enter filename:")
#attempt to open file for readingtry:
fobj = open(fname,'r')
except:
print ("'%s' open error or the file does not exit" % fname)
else:
#display content to the screenfor eachLine in fobj:
print (eachLine)
fobj.close()