Python3上传中文文件名的问题

Python014

Python3上传中文文件名的问题,第1张

我们之前在Python2.x的时候,用requests上传文件是正常存储中文名字,但是使用Python3之后,文件名就变得不正常了。因为Java服务端接口不支持这种方式,于是只能修改Python脚本。

因为Python3使用requests的时候,会调用urllib3库—>fields.py的新处理逻辑

当文件名是中文的时候, value = email.utils.encode_rfc2231(value, 'utf-8') 就会转换格式为:

filename* 这种格式的键值对。

当然改源码文件是最快的,但是这样不利于移植。

还是修改下requests请求吧。

python 读写文件:

data_json = json.dumps(result_r)  #json字符串  

f =open('E://XXX.txt',"a+")  #打开文件,追加+读写

f.write(data_json) # data_json 写入XXX.txt'文件

f.seek(0)  # 光标移动到文件开头

lines = f.read() # 逐行读入

f.close() #关闭文件

mode 打开的方式(r,w,a,x,b,t,r+,w+,a+,U)

r 以只读方式打开文件。文件的指针会放在文件的开头。

w 以写入方式打开文件。文件存在覆盖文件,文件不存在创建一个新文件。

a 以追加方式打开文件。如果文件已存在,文件指针放在文件末尾。如果文件不存在,创建新文件并可写入。

r+ 打开一个文件用于读写,文件指针会放在文件的开头

w+ 打开一个文件用于读写,文件存在覆盖文件,文件不存在创建一个新文件。

a+ 打开一个文件用于读写,如果文件已存在,文件指针放在文件末尾。如果文件不存在,创建新文件并可写入。

记忆方法:记住r读,w写,a追加,每个模式后加入+号就变成可读写。

f =open('E://xxx.txt',"a+")    /    f=open(r'E://xxx.txt',mode='a+',encoding='UTF-8')

踩坑1>  

没有加encoding='UTF-8',可能会报如下错:

import requests  # 使用 request函数需导入 request 库

import json   #使用 JSON 函数需要导入 json 库: import json 。

param ={} #请求body

url ='http://域名/api' 

header = {'content-type':'application/json'}

r = requests.post(url,json=param,headers=header)    #发送post请求

result_r = r.json() #请求返回的json传入对象result_r

data_json = json.dumps(result_r)  #将 Python-result_r对象转为字符串 json.dumps()

文件上传请求(csv文件)

file_path = "xxx.csv"   文件路径

uploaddata = {"file":open(file_path, "rb")}  

file_upload_result = requests.post(api_URL, files=uploaddata, cookies=cookie)

以下是单个文件的,不确定你的文件夹是什么意思,可以压缩下再上传(方法一样,调用zip命令)

我的实现方法:调用终端的curl,以下为代码平片段,实现的功能是上传log文件到服务器,供参考:

def post_log(self, post_url, del_source_file=True):

        '''

        post log to log server

        '''

        if self.log_path:

            command = "curl -s -F log=@{0} {1}".format(self.log_path, post_url)

            return_str = os.popen(command).read()

            logging.debug(return_str)

            # print return_str

            if return_str == "success":

                if del_source_file:

                    del_command = "sudo rm {0}".format(self.log_path)

                    os.system(del_command)

                return True

            else:

                return False

        return False