2016-06-09 166 views
1

我写了一段代码,它使用get请求以文本文件的形式从API接收响应。这个文件包含一个用base64编码的二进制文件,这对我很感兴趣。我希望能够使用Python从文件中仅提取此二进制文件,以便我可以对其进行解码。删除Python中某个字符串之前和之后的字符

我当前的代码是:

response = requests.get(url, headers=header, verify=False) 

    #Decoding response from base64 
    decoded_response = base64.b64decode(response) 

    #Printing response 
    print decoded_response.text 

    #Writing response to a file 
    f = open("decoded_response.txt","w") 
    f = f.read() 
    pickle.dump(decoded_response, f) 
    f.close() 

这是抛出一个TypeError,因为编码的字符串需要被移除以base64开始之前填充预期。 寻求帮助!

Beginning of file

+1

我知道这是不是答案,而是一个建议,因为我在Python不代码(我JS,Ruby和Java中的代码)。我会解决这个问题,而不是删除文本,但**使用**正则表达式**提取**文本以获取我想要的部分(这将是base64内容),然后解码它。但是,我不知道内容有多大,以及在提取内容时会如何影响性能。 –

回答

0

以下修改后的代码为我工作:

f = open("response.txt","wb") 
f.write(json.loads(response.text)['Binary'].decode('base64')) 
f.close() 
相关问题