1、操作目錄與檔案名稱
#!/usr/bin/env python #-*- coding: utf-8 -*- import os,re import shutil import time
#用listdir搜尋
def search_OFD_old(my_pattern, diretory): try: names = os.listdir(diretory) except os.error: print "error" return for name in names: fullname = os.path.normpath(os.path.join(diretory, name)) if os.path.isfile(fullname): result = my_pattern.search(name) if result and name.lower().endswith("txt"): shutil.copy(fullname, dest_dir) elif os.path.isdir(fullname): search_OFD(my_pattern, fullname)#########用walk函數搜尋#########
def search_OFD(my_pattern, diretory): for root,dirs,files in os.walk(diretory): for filename in files: result = my_pattern.search(filename) if result and filename.lower().endswith("txt"): fullname = os.path.join(root, filename) shutil.copy(fullname, dest_dir)#########目錄不存在,則建立:####### ##
if not os.path.isdir(dest_dir): os.makedirs(dest_dir)#########匹配名稱#########
import re pattern = re.compile("1ABC") pattern.search(var)###更多python目錄與檔案名稱操作相關文章請關注PHP中文網! ############