Quote:
Originally Posted by chaley
Looks mostly good.
Some comments:
- Why did you create the temp file for the txt format instead of simply using its path? EDIT: ahhh, I see. You created an empty txt file to avoid the necessity of passing one in as an argument or having one sitting around.
|
Yep. I wanted to limit the number of named paths to be user-edited.
Quote:
- You should first get the IDs that don't have a TXT format and add it only to them. Use something like cache.search('not formats:=TXT'). This is where the user could also add some criteria, such as doing it only if a book has a certain tag.
|
Good idea.
Um... add_format does have a "replace=True" default, so I guess we could just use:
Code:
for id in cache.all_book_ids():
cache.add_format(id, 'TXT', temporary_txt_file, replace=False)
We could do a search instead, or in addition (because I am still wary of overwriting another TXT) if I thought this script was going to get a lot of use. Heck, let's do it anyway.
Quote:
- You might want to put try/except around the add_format
- Is it worth checking add_format's returned value and printing an error?
|
Hmm, I don't know. Checking the source for add_format, it returns true unless early on it sees there is already a copy of that format AND replace=False.I guess it assumes the function will never error out, possibly because it shouldn't ever do so.

But if we are to limit to a search of not formats:"=TXT" then we will never get it.
Using your print modifications as well.
Code:
def init_cache(library_path):
from calibre.db.backend import DB
from calibre.db.cache import Cache
backend = DB(library_path)
cache = Cache(backend)
cache.init()
return cache
print('Creating temporary TXT file')
import tempfile
temporary_txt_file = tempfile.NamedTemporaryFile(suffix='txt', delete=False)
from calibre.utils.config import prefs
library_path = prefs['library_path']
print('Initializing database')
cache = init_cache(library_path)
print('Begin looping through books')
failed_books = 0
ids = 0
for id in cache.search('not formats:"=TXT"'):
ids += 1
try:
cache.add_format(id, 'TXT', temporary_txt_file, replace=False)
except:
failed_books+=1
print('Failed to add TXT format for book with id', id)
print('Finished adding TXT format to', ids, 'books')
if failed_books > 0:
print(failed_books, 'books did not have a TXT format added')
Anyway, good to hear it worked, thanks chaley for helping out while I was offline.
Do not worry about being unable to get it at first. It isn't in your skillset, and you are hardly unusual in that regard. I probably should've mentioned in the first place that you will need Notepad.
It would help if Windows wasn't so eager to rid the world of file extensions.
Attached is the actual file, redundant though it may now be

-- rename to .py (we really should be able to attach any file we want).
EDIT: Updated to use calibre's internal preferences to choose the library. No need to edit anything.