python创建文件

来源:互联网 发布:文件数据库 sqlite 编辑:程序博客网 时间:2024/06/06 08:29


这个脚本提示用户输入一个(尚不存在的)文件,然后由用户输入该文本的每一行,最后,将所有文本写入文本文件。

import osls=os.linesepwhile True:    fname=raw_input("Enter the the file name:")    if os.path.exists(fname):        print "Error,the file exists"    else:        breakall=[]print "\nEnter liines('.'by itself to quit).\n"while True:    entry=raw_input('> ')    if entry=='.':        break    else:        all.append(entry)fobj=open(fname,'w')#fobj.writelines(['%s%s'%(x,ls) for x in all])fobj.writelines((['%s'%x for x in all]))fobj.close()print 'Done!'
运行结果如下:
C:\Anaconda2\python.exe C:/Users/Auser.MEY/PycharmProjects/test1/test.pyEnter the the file name:C:\\Users\\Auser.MEY\\Desktop\\gooog.txtEnter liines('.'by itself to quit).> hello success> .Done!Process finished with exit code 0

C:\\Users\\Auser.MEY\\Desktop路径下创建了一个名为gooog的txt文档,同时写入了hello success的内容
<img src="http://img.blog.csdn.net/20160726154711189?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

如果输入多行数据,我们的目标是在文本文件中显示多行,因此需要插入行终止符,源程序部分需要进行修改。

fobj.writelines(['%s%s'%(x,ls) for x in all])
C:\Anaconda2\python.exe C:/Users/Auser.MEY/PycharmProjects/test1/test.pyEnter the the file name:C:\\Users\\Auser.MEY\\Desktop\\Test.txtEnter liines('.'by itself to quit).> hello python> I love you.> Thanks a lot> .Done!Process finished with exit code 0

结果如下:


0 0