最近在寫一個(gè)腳本雁刷,在使用python在上傳文件之后,移動(dòng)文件到另一文件夾保礼,過程中遇到了Bug沛励。
首先百度了一下,各種博客中炮障,關(guān)于requests上傳的代碼基本都類似:
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
當(dāng)requests.post返回后目派,接著執(zhí)行shutil.move(file_path, dest_dir)
時(shí),大概率報(bào)出如下錯(cuò)誤:[WinError 32] 另一個(gè)程序正在使用此文件
仔細(xì)思考了下胁赢,其實(shí)這些教程的代碼都不嚴(yán)謹(jǐn)企蹭,open之后沒有close。于是在代碼中加入了with語句,自動(dòng)close之:
def post_file(url, file_path):
with open(file_path, 'rb') as f:
result = requests.post(url, files={'file': f})
return result