为什么我的文件编写方法不起作用?

时间:2015-10-11 19:12:19

标签: python file file-writing

import os

books = open(os.path.expanduser("~/Desktop/books.txt")).read()
b= books.split('\n')
del b[-1]
book={}
for i in b:
    b1=i.split('\t')
    book[b1[0]]=[b1[1],b1[2],b1[3]]

def all_book():

    print "The Book List" 
    books = open(os.path.expanduser("~/Desktop/books.txt")) 
    print books.read()

def add_book():

    print "Registering New Book"
    books = open(os.path.expanduser("~/Desktop/books.txt"))
    name = raw_input("Title: ") 
    author= raw_input("Author Name: ") 
    publisher =raw_input("Publisher: ") 
    n= int(b1[0])
    n1 = n+1
    newb= [str(n1), '\t', name, '\t', author,'\t', publisher] 
    books.writelines(newb) #Adding file to the list
    newb = {}
    newb[n1]=[name, author, publisher] 
    print 'A New Book Added!' 
    return newb

def del_book():

    print "Deleting Books" 
    delnum = str(raw_input("Registered Number:"))
    if delnum in book:
        del book[delnum]
    else:
        print delnum, "Not Found"


def show_menu():

    print '''
    1) add new
    2) all show
    3) delete
    4) search
    5) Save/out
    '''
    menu_choice = raw_input('what --> ')
    if menu_choice == '1':
            add_book()
    elif menu_choice == '2':
            all_book()
    elif menu_choice == '3':
            del_book()

show_menu()

2 个答案:

答案 0 :(得分:1)

books = open(os.path.expanduser("~/Desktop/books.txt")).read()

你的错误就在这里。如果您没有指定文件打开模式,Python将默认为' read'模式,意味着你不能写它。 打开文件进行写入的正确语法是:

books = open('file', 'w')

This page在页面下方有一个文件访问模式表。

答案 1 :(得分:0)

open()默认将文件打开,这就是为什么您无法将新书写入文本文件。