您的位置:首页 > 编程语言 > Python开发

Python 读写文件的两个简单实例

2014-10-21 15:02 429 查看
写:

import os

# get filename
while True:
filename = raw_input("Please input file name: ")
if os.path.exists(filename):
print 'Error: "%s" exists' % filename
else:
break

# get file content
all = []
print "Enter lines '.' to quit.\n"

# loop until user terminate input
while True:
line = raw_input('> ')
if line == '.':
break
else:
all.append(line)

# write line to file
fobj = open(filename, 'w')
fobj.write('\n'.join(all))
fobj.close()

print 'Done!'


读:

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

# attemp to open file for reading
try:
fobj = open(fname, 'r')
except IOError, e:
print "*** file open error:", e
else:
# display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: