1.背景
最近學習中國大學MOOC的課程,想把課程的pdf下載下來本地保存並瀏覽。工具: Setup-Mooc-3.4.0.exe
但是,卻發現所下載的文檔在不同的文件夾里,瀏覽很不方便。於是寫個腳本復制粘貼課件到指定位置。
2.工作
2.1 獲取指定目錄中所下載的文件名
files=[]
#獲取指定目錄下的文件名
def get_file_dir(dir):
if os.path.isdir(dir):
for item in os.listdir(dir):
if item!='System Volume Information':#windows下沒權限刪除的目錄:可在此添加更多不判斷的目錄
get_file_dir(os.path.join(dir, item))
else:
files.append(dir)
path=r'C:\Users\Administrator\Downloads\Programs\學無止下載器-v1.1.0\Download'
get_file_dir(path)
2.2 粘貼復制並重命名文件
course='離散數學 北交大 劉鐸'
#newpath=r''+'\\'+course #合並的文件存放位置
new_path=r''+'\\'+course+'\課件' #復制的文件存放位置
for file in files:
old_name=os.path.split(file)[1]
new_name=re.sub('[()--—_課件]','',old_name)
shutil.copy(file,os.path.join(new_path,new_name))
2.3 文件合並
def mergepdf(new_path,course,newpath):
pdfs=os.listdir(new_path)
merger = PdfFileMerger()
for pdf in pdfs:
merger.append(open(os.path.join(new_path,pdf), 'rb'))
with open(newpath+'\\'+course+'.pdf', 'w+') as fout:
merger.write(fout)
值得注意的是,這里程序會報錯,如下:

在網上看到一些文章提及編碼方式改成“GBK”,可在一定程度上解決問題(但也可能出現亂碼)。這里沒有嘗試,我直接用Adobe Arcobat Pro DC合並。
2.4 結果

3.最后
對於本腳本,我后來進行了優化(文件夾新建、命令行輸入參數),下載鏈接:mooc_pdf_cmd
若有問題,請私信我。
