最近在寫一個腳本,在使用python在上傳文件之后,移動文件到另一文件夾,過程中遇到了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)時,大概率報出如下錯誤:[WinError 32] 另一個程序正在使用此文件
仔細思考了下,其實這些教程的代碼都不嚴(yán)謹,open之后沒有close。于是在代碼中加入了with語句,自動close之:
def post_file(url, file_path):
with open(file_path, 'rb') as f:
result = requests.post(url, files={'file': f})
return result