这个脚本提示用户输入一个(尚不存在的)文件,然后由用户输入该文本的每一行,最后,将所有文本写入文本文件。
import os
ls=os.linesep
while True:
fname=raw_input("Enter the the file name:")
if os.path.exists(fname):
print "Error,the file exists"
else:
break
all=[]
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.py
Enter the the file name:C:\\Users\\Auser.MEY\\Desktop\\gooog.txt
Enter 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="https://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.py
Enter the the file name:C:\\Users\\Auser.MEY\\Desktop\\Test.txt
Enter liines('.'by itself to quit).
> hello python
> I love you.
> Thanks a lot
> .
Done!
Process finished with exit code 0
结果如下: