-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathebookRename.py
60 lines (48 loc) · 1.61 KB
/
ebookRename.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# encoding=utf-8
import sys
import os.path
import getopt
from kindleunpack.utf8_utils import utf8_argv, add_cp65001_codec, set_utf8_default_encoding, utf8_str
from kindleunpack.mobi_sectioner import Sectionizer, describe
from kindleunpack.mobi_header import MobiHeader, dump_contexth
def getMobiFileName(infile):
""" 存在问题, """
sect = Sectionizer(infile)
if sect.ident != 'BOOKMOBI' and sect.ident != 'TEXtREAd':
raise 'Invalid file format'
mh = MobiHeader(sect,0)
# Error: Updated_Title 可能不存在,但 calibre 能得到标题
titles = mh.metadata.get('Updated_Title')
if not titles:
print('无法得到标题')
return
title = titles[0]
title = title.decode(mh.codec)
author = '、'.join([au.decode(mh.codec) for au in mh.metadata['Creator']])
return '%s - %s' % (title, author)
def renameOneBook(infile):
parentDir = os.path.dirname(infile)
oldName = os.path.basename(infile)
ext = os.path.splitext(oldName)[1]
newName = None
if ext in ['.epub']:
pass
elif ext in ['.azw3', '.azw4', '.azw', '.mobi']:
newName = getMobiFileName(infile)
if newName:
newName += ext
if newName == oldName:
return
os.chdir(parentDir.decode('utf-8').encode('gbk'))
print('%s -> %s' % (oldName, newName))
os.rename(oldName, newName)
def main(argv=utf8_argv()):
if len(argv) == 1:
sys.exit(2)
else:
for path in argv[1:]:
renameOneBook(path)
if __name__ == '__main__':
add_cp65001_codec()
set_utf8_default_encoding()
sys.exit(main())