python 文本的讀寫功能整合

功能整合
程序如下:
print("*creating and reading text file in on programe*")
while True:
    print("\n=========Meau======")
    print("a. create text file")
    print("b. read text file")
    print("q. quit")
    print(" "*11,"All by Neo")
    print('- '*10)
    choice = input("\nWhat do U want ?:")

    if  choice == 'a':
        print("\n\n***create text file***")
        import os
        ls = os.linesep
        #get filename
        while True:
            fname = input("Enter your file name:")
            if os.path.exists(fname):
                judge = input("File already exists,try to overwrite it(y/n)?:")
                if judge == 'y':
                    os.remove(fname) #if 'y' ,remove old file
                    break
                if judge == 'n':
                    break
            else:
                break

        #get file content lines
        all = []
        print("\nEnter your lines('quit'by itself to quit).")
        while True:
            entry= input('>')
            if entry == 'quit':
                break
            else:
                all.append(entry)
 
        #write lines to file with proper line-ending
        fobj = open(fname, 'w')
        fobj.writelines(['%s%s' %(x,ls) for x in all])
        fobj.close()
        print('Done')

    if choice == 'b':
        #read and display text file
        print("\nread and display text file")
        fname = input("\n\nEnter the filename:")
        print
 
        #attemp to open file for reading
        try:
            fobj = open(fname,'r')
        except IOError:
            print("file open error:")
        else:
            #display contents
            print('- '*5,"contents below",'- '*5)
            for eachline in fobj:
                print(eachline,end = '')
            fobj.close()
        print('- '*7,"Done",'- '*7)
 
    if choice == 'q':
        break
 
print ("\nDone,bye")
           
程序功能有限
對文本的編輯功能尚在學習中
try more
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章