requests上传文件后移动,提示:[WinError 32] 另一个程序正在使用此文件

最近在写一个脚本,在使用python在上传文件之后,移动文件到另一文件夹,过程中遇到了Bug。

首先百度了一下,各种博客中,关于requests上传的代码基本都类似:

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

当requests.post返回后,接着执行shutil.move(file_path, dest_dir)时,大概率报出如下错误:[WinError 32] 另一个程序正在使用此文件

仔细思考了下,其实这些教程的代码都不严谨,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

你可能感兴趣的:(requests上传文件后移动,提示:[WinError 32] 另一个程序正在使用此文件)