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()
相關文章
相關標籤/搜索