python 学习记录

添加新功能。将你上一个问题改造好的 readNwriteTextFiles.py 增长一个新功
能:容许用户编辑一个已经存在的文本文件。 你能够使用任何方式,不管是一次编辑一行,还
是一次编辑全部文本。须要提醒一下的是, 一次编辑所有文本有必定难度,你可能须要借助 GUI
工具包或一个基于屏幕文本编辑的模块好比 curses 模块。要容许用户保存他的修改(保存到
文件)或取消他的修改(不改变原始文件),而且要确保原始文件的安全性(不论程序是否正
常关闭)。

本身刚刚接触python,因此写的有点土,望大侠们多指点:
import os

ls=os.linesep
#get filename

    
fname=raw_input('please input file name:')
all=[]

if os.path.exists(fname):
    fwrite=open(fname,'r')
    Lines=fwrite.readlines()
    all.extend(Lines)

        

#get file content(text) lines

print "\n Enter lines('.' by itself to quit).\n"
#loop until user terminates input
while True:
    entry=raw_input('pleaseinput content')
    ifentry=='.':
        break
    else:
        all.append(entry)
    printall
#write lines to file with proper line-ending
while True:
    test=raw_input('youare sure to save this file?')
    iftest=='yes':
        fobj=open(fname,'w')
        fobj.writelines(['%s%s'%(x,ls)forx in all])
        fobj.close()
        print'Done'
    eliftest=='no':
        print'no need to write'
        break
    else:
        print'please input right words to judge:'


try:
    fobj=open(fname,'r')
except IOError,e:
    print'***file open error',e
else:
    foreachLine in fobj:
        printeachLine,
    fobj.close()
相关文章
相关标签/搜索