python--writefile&readfile

 

writefile

#!/usr/bin/env python
'makeTextFlie.py --create text file'
import os
ls = os.linesep
#get filename
fname = raw_input('input your file name:\n')
while True:
    if os.path.exists(fname):
        print "error: '%s' already exists\n" % fname
    else:
        break
#get file content lines
all = [] #get list
print "enter line ('.'by itself to quie).\n"
#loop until user terminates input
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.close()
print 'DONE'

readfile

#!/usr/bin/env python
'readTextFlie.py --create text file'
import os
ls = os.linesep
#get filename
fname = raw_input('input your file name\n')
try:
    fobj = open(fname, 'r')
except IOError, e:
    print 'open file error:\n',e
else:
    for eachline in fobj:
        print eachline,
    fobj.close()

 

转载于:https://www.cnblogs.com/Pierre-de-Ronsard/archive/2012/08/10/2632005.html

你可能感兴趣的:(python--writefile&readfile)