How to load cookies from a text file in python requests

Question:

I’ve been trying to load raw cookies (not json) but using a txt file instead of declaring it directly inside a variable but getting no success , Here’s my code ->

cookies.txt

{"PHPSESSID": "ibd1biktq4tfm3k4j790juf19d", "security": "impossible"}

my python script

file = open("cookies.txt", "r")
file = file.readlines()
str1 = " "
cookies = str1.join(file)     # for converting list into string
requests.get("http://localhost/dvwa", cookies=cookies)

output : TypeError: string indices must be integers

Also if i do print(cookies) it outputs {"PHPSESSID": "ibd1biktq4tfm3k4j790juf19d", "security": "impossible"} and declaring the same output directly into the variable "cookies" works …

Can anyone please clarify what i am doing wrong ?

Asked By: Dang Max

||

Answers:

Try to parse the string to Python dictionary using ast.literal_eval:

from ast import literal_eval

with open("cookies.txt", "r") as f_in:
    cookies = literal_eval(f_in.read())

requests.get("http://localhost/dvwa", cookies=cookies)
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.