我有点困惑,但是直接在请求中打开文件(但是官方请求指南中也写了同样的内容)并不是那么“安全”。
试试看嘛:
import os
import requests
file_path = "/home/user_folder/somefile.txt"
files = {'somefile': open(file_path, 'rb')}
r = requests.post('http://httpbin.org/post', files=files)
是的,一切都会好的,但是:
os.rename(file_path, file_path)
你会得到:
PermissionError:The process cannot access the file because it is being used by another process
如果我不正确,请纠正我,但似乎该文件仍处于打开状态,我不知道有什么方法可以关闭它。
而不是这个我使用:
import os
import requests
#let it be folder with files to upload
folder = "/home/user_folder/"
#dict for files
upload_list = []
for files in os.listdir(folder):
with open("{folder}{name}".format(folder=folder, name=files), "rb") as data:
upload_list.append(files, data.read())
r = request.post("https://httpbin.org/post", files=upload_list)
#trying to rename uploaded files now
for files in os.listdir(folder):
os.rename("{folder}{name}".format(folder=folder, name=files), "{folder}{name}".format(folder=folder, name=files))
现在我们没有收到错误,所以我建议使用这种方式上传多个文件,否则您可能会收到一些错误。希望这个答案能很好地帮助别人并节省宝贵的时间。