python遍歷資料夾種的檔案,篩選複製,txt寫
阿新 • • 發佈:2018-12-17
import os, shutil # 規範化絕對路徑 src_dir = os.getcwd() #得到當前py檔案的路徑 # if not os.path.exists(dst_dir): # os.makedirs(dst_dir) # print("fistr_dir is:\t{}".format(fistr_dir)) if os.path.exists(src_dir): # root 所指的是當前正在遍歷的這個資料夾的本身的地址 # dirs 是一個 list,內容是該資料夾中所有的目錄的名字(不包括子目錄) # files 同樣是 list, 內容是該資料夾中所有的檔案(不包括子目錄) for dirnames, dirs, files in os.walk(src_dir): for filename in files: if filename.endswith('.pdf'): 判斷是否該字尾 if ( (filename != "paper.pdf") and (filename != "marked.pdf")): fub_dir = dirnames +'\\'+ filename #與os.path.join一樣 print(fub_dir) new_file = os.path.join(dirnames, "paper.pdf") print(new_file) os.rename(fub_dir, new_file) #檔案重新命名 shutil.copyfile(new_file, os.path.join(dirnames, "marked.pdf")) # txt-insert if( filename == "ref.txt"): fub_dir = dirnames + '\\' + filename print(fub_dir) fp = open(fub_dir) #讀取 lines = [] for line in fp: lines.append(line) fp.close() lines.insert(-1, 'affiliation = { | }') # 在倒數第二行插入 s = ''.join(lines) fp = open(fub_dir, 'w') fp.write(s) #寫入 fp.close() print('over!')