1這是一個創建一個文件,並在控制台寫入行到新建的文件中.
#!/usr/bin/env python
'makeTextFile.py -- create text file'
import os
ls = os.linesep
#get filename
while True:
fname = raw_input('Enter filename:')
if os.path.exists(fname):
print "ERROR: '%s' already exists" % fname
else:
break
#get file content (text) lines
all = []
print "\nEnter lines('.' by itself to quit).\n"
#loop until user terminates input
while True:
entry = raw_input('>')
if entry == '.':
break
else:
all.append(entry)
#write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE!'
os.linesep表示行結尾標志, 用本地變量名ls代替它節省了時間,並減少了消耗系統資源.
用 raw_input()讀入文件名
用列表all[]來保存每一行文本(它們暫時在內存中).
最後創建文件後,用writelines()把內存中的行寫入打開的文件中.