[python]创建文本文件,并读取

代码如下:

# 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

 

 

你可能感兴趣的:([python]创建文本文件,并读取)