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

python写的读写文件的脚本

2012-05-23 21:38 561 查看
一边学习python,一边练习python。这是一个好的学习方法。

下面这个脚本是根据课后题写的,吸收了别人的一些经验。只是一个很简单的脚本,大牛勿笑。

################################
#  Author :   netcat           #
#    QQ   :   297020555        #
#   Date  :   2012-1-3         #
# Version :   1.0              #
# Function: to read&write file #
################################

import os
ls=os.linesep

numlist=['1','2','3']
def getnum():
input=raw_input('''
---------------------
1.read
2.write
3.quit
---------------------
enter your select num:\n''')
if input in numlist:
return input
else:
print 'enter error,input again'
return getnum()

def getfile():
file=raw_input('enter filename:\n')
return file

def comment():
print 'enter "quit" to exit'
lines=[]
line=raw_input('>')
while True:
if line=='quit':
return lines
else:
lines.append(line)
line=raw_input('>')

def write():
if os.path.exists(file):
f=open(file,'a')
f.writelines(['%s%s'%(x,ls) for x in com])
f.close()
print 'append done'
else:
f=open(file,'w')
f.writelines(['%s%s'%(x,ls) for x in com])
f.close()
print 'write done'

def read():
if os.path.exists(file):
f=open(file,'r')
for line in f:
print line,
else:
print 'file is not exists'

while True:
num=getnum()
if num=='1':
file=getfile()
read()
elif num=='2':
file=getfile()
com=comment()
write()
else:
print 'exit'
break
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: