先介紹兩個函數:
一。os.walk()可以得到一個三元tupple(dirpath,sub_dirs, filenames),其中第一個為起始路徑,第二個為起始路徑下的檔案夾,第三個是起始路徑下的檔案。
其中dirpath是一個string,代表目錄的路徑,sub_dirs是一個list,包含了dirpath下所有子目錄的名字。filenames是一個list,包含了非目錄檔案的名字。這些名字不包含路徑資訊,如果需要得到全路徑,需要使用os.path.join(dirpath, name).
二。withopen(spcial_file_dir)assource_file
with 語句是在 Python 2.5 版本引入的,從 2.6 版本開始成為預設的功能。
with 語句作為 try/finally 編碼範式的一種替代,用於對資源訪問進行控制的場合。
如果要開啟檔案並保證最後關閉他,只需要這麼做:
withopen("x.txt") as f: data=f.read() do something with data
with-as運算式極大的簡化了每次寫finally的工作,無需自己手動將開啟檔案close()掉 若要更深理解: http://zhoutall.com/archives/325
http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/ 掃描目錄讀取檔案,不考慮子目錄情況
try: source_dir = '/dir/source/' target_dir = '/dir/old/' for root, sub_dirs, files in os.walk(source_dir): for special_file in files: spcial_file_dir = os.path.join(root, special_file) # 開啟檔案的兩種方式 # 1.檔案以絕對路徑方式 with open(spcial_file_dir) as source_file: # 2.檔案以相對路徑方式 # with open(r'dir_test/test.txt') as source_file: for line in source_file: # do something # 移動檔案 shutil.move(spcial_file_dir, target_dir) logger.info(u'檔案%s移動成功'% spcial_file_dir) return HttpResponse(json.dumps({'result':0}))except Exception as e: # do something