使用者輸入原資料夾所在的路徑。若路徑存在則將 working directory 設為使用者輸入的路徑,若路徑不存在則印出警告訊息。
1
2
3
4
5
6
7
path1='123'whilepath.exists(path1)==False:path1=input('Please enter the location of the original files:')ifpath.exists(path1):os.chdir(path1)# Set working directoryelse:print('Warning: Invalid path')
# A function that extracts files that match the patterndefsearch_file(filename,pattern):doc=docx.Document(filename)text=[]forparaindoc.paragraphs:text.append(para.text)ifre.findall(pattern,str(text))!=[]:returnfilenameelse:return0
1
2
3
4
5
6
7
8
# Search docx files with content matching particular patternpattern=input('Please enter the keyword')matched_files=[]forfileinos.listdir():ifnotfile.endswith('.docx'):continuex=search_file(file,pattern)ifx!=0:matched_files.append(x)
# A function that manipulates files (move, copy, or delete)deffile_manipulate(mode,matched_file_path,to):ifmode=='move':shutil.move(matched_file_path,to)elifmode=='copy':shutil.copy(matched_file_path,to)elifmode=='delete':os.remove(matched_file_path)else:return'no such mode'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
mode='123'whilemodenotin['move','copy','delete']:mode=input('move, copy, or delete?')ifmode=='delete':to=''formatched_file_pathinmatched_files_paths:file_manipulate(mode,matched_file_path,to)elifmodein['move','copy']:to=input("Please provide the new file path")ifpath.exists(to)==False:print('Warning: Invalid path')else:formatched_file_pathinmatched_files_paths:file_manipulate(mode,matched_file_path,to)else:print('Warning: Invalid mode')
Murmuring
真心覺得對初學者來說,盡量不要同時學兩個程式。資質駑鈍如我無法同時參透兩個語言,因此這學期就是不斷把 R 寫在 python 裡或把 python 寫在 R 裡。寫完一整天的 python 要再回去寫 R,簡直像濃霧中漫步伸手不見五指。順攝抑制和倒攝抑制在我身上嶄露無遺。所以學程式不要貪快貪多,會消化不良(倘若列位看官是程式小天才則另當別論)。像這個簡單的小專案就讓我做了超級久(從適應 python 語法到寫出好像可以 run 的東西),而且還不大完善。最好的方式就是早一點開始學,不要像我一樣 code 到用時方恨少!