Python 为什么我的文件编写方法不起作用?
打开默认值以读取方式打开文件,这就是为什么不能将新书写入文本文件Python 为什么我的文件编写方法不起作用?,python,file,file-writing,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 Bo
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()
你的错误就在这里。如果不指定文件打开模式,Python将默认为“读取”模式,这意味着您无法对其进行写入。
打开文件进行写入的正确语法为:
books = open(os.path.expanduser("~/Desktop/books.txt")).read()
在页面下方有一个文件访问模式表 添加\u此处的书不起作用我尝试了2个小时,但失败了..ha newb=[strn1',\t',name',\t',author',\t',publisher]books.writelinesnub将文件添加到列表请修复缩进,如果有错误消息,请告诉我们,并使用更具描述性的标题@Naeun Kim:为了进行合成着色,每行缩进额外的4个空格。请描述哪些不起作用。
books = open('file', 'w')