现在的位置: 首页 > 综合 > 正文

Python 的文件读写

2012年01月24日 ⁄ 综合 ⁄ 共 564字 ⁄ 字号 评论关闭

写文件

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()

抱歉!评论已关闭.