Skip to content Skip to sidebar Skip to footer

Save A List To A File

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: d

Solution 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.

Solution 2:

First off, here's an easier way to read, assuming those eight fields are the only ones:

defread_bookfile(filename="a.txt"):
    withopen(filename) as f:
        return [Book(*line.split('/')) for line in f]

Now, to save:

defsave_bookfile(booklist, filename='a.txt'):
     withopen(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 with statement 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 doing lst = []; 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 * in read_bookfile splits 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 did str(isbn) (because book.isbn is an int).

Solution 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:

Solution 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()

Post a Comment for "Save A List To A File"