Python 的文件读写

写文件

import os
ls=os.linesep

#get filename
fname=raw_input('Enter file name: ')
if os.path.exists(fname):
print "Error:"+fname

#get file content
all=[]
print "\nEnter lines ('.' by itself to quit).\n"

while True:
entry=raw_input('> ')
if entry=='.':
break
else:
all.append(entry)
#write file
print all
fobj=open(fname,'w')
fobj.writelines(['%s%s' % (x,ls) for x in all])
fobj.close()
print 'Done'

读文件

#!/usr/bin/env python

'ReadFile.py -- Read text file'

#get filename
fname=raw_input('Enter file name: ')
print

#read file content
try:
fobj=open(fname,'r')
except IOError,e:
print "open error",e
for eachline in fobj:
print eachline,
fobj.close()



你可能感兴趣的:(python)