问题
I have a library where I want to create a new book and then add it to my list of books. What I have problems with is to save the file between calls.
This is how I read the file:
def read_bookfile():
try:
booklibrary_file = open("a.txt")
booklibrary_list = []
booklist = booklibrary_file.readlines()
for rad in booklist:
linelist = rad.split("/")
title = linelist[0]
firstname = linelist[1]
lastname = linelist[2]
isbn = int(linelist[3])
availability = linelist[4]
borrowed = linelist[5]
late = linelist[6]
returnday = linelist[7]
b = Book(title, firstname, lastname, isbn, availability, borrowed, late, returnday)
booklibrary_list.append(b)
booklibrary_file.close()
return booklibrary_list
Now I want to know how to save to my file.
回答1:
In order to save to a file, you have to open it in Write-Append mode.
library_file = open("a.txt", "a")
...
library_file.write("Some string\n")
...
library_file.close()
Refer to Python's documentation on Built-in Functions for more information.
回答2:
First off, here's an easier way to read, assuming those eight fields are the only ones:
def read_bookfile(filename="a.txt"):
with open(filename) as f:
return [Book(*line.split('/')) for line in f]
Now, to save:
def save_bookfile(booklist, filename='a.txt'):
with open(filename, 'w') as f:
for book in booklist:
f.write('/'.join([book.title, book.firstname, book.lastname, str(book.isbn),
book.availability, book.borrowed, book.late, book.returnday])
+ '\n')
assuming the Book model just saves those attributes in as they were passed (as strings).
Explanations:
- The
withstatement opens your file and makes sure that it gets closed when control passes out of the statement, even if there's an exception or something like that. - Passing in the filename as an argument is preferable, because it allows you to use different filenames without changing the function; this uses a default argument so you can still call it in the same way.
- The
[... for line in f]is a list comprehension, which is like doinglst = []; for line in f: lst.append(...)but faster to write and to run. - Opening a file in
'w'mode allows you to write to it. Note that this will delete the already-existing contents of the file; you can use'a'or'w+'to avoid that, but that requires a little more work to reconcile the existing contents with your book list. - The
*inread_bookfilesplits a list up as if you passed them as separate arguments to a function. '/'.join()takes the list of strings and joins them together using slashes:'/'.join(["a", "b", "c"])is"a/b/c". It needs strings, though, which is why I didstr(isbn)(becausebook.isbnis an int).
回答3:
Python is "batteries included", remember?
Consider using the "csv" module:
use csv
csv.reader(...)
csv.writer(...)
I think these have lots of options (like you can set your delimiters to be other than commas; you can read in to a list of dictionaries, etc.)
See Python Docs for CSV reader/writer:
回答4:
I have to make a few assumptions about your Book class, but I think this might help put you on the right track:
bookList = read_bookfile()
outfile = open("booklist.txt", "w")
for book in bookList:
bookStr = book.title + " " + book.firstname + " " + book.lastname + " " + book.isbn + " " + book.availability + " " + book.borrowed + " " + book.late + " " + book.returnday + "\n"
outfile.write(bookStr)
outfile.close()
来源:https://stackoverflow.com/questions/10419417/save-a-list-to-a-file