首页 > 技术文章 > [python]创建文本文件,并读取

sophia194910 2015-12-29 12:43 原文

代码如下:

# coding=gbk
import os

fname = raw_input("Please input the file name: ")
print

if os.path.exists(fname):
    print "ERROR: '%s' already exists!!!" % fname
    
    
text = []
print "Input '.' to end input!).\n"

while True:
    entry = raw_input('>')
    if entry == '.':
        break
    else:
        text.append(entry)
        
fobj = open(fname, 'w')
fobj.writelines(['%s\n' % (x) for x in text])
fobj.close()
print 'DONE'

运行结果如下:


Please input the file name: 1229.txt


Input '.' to end input!).


>hello world!
>Today is Tuesday!
>I'm happy!
>.
DONE

 

 

推荐阅读