E.Belekov
E.Belekov

Reputation: 547

Python writes questions instead of string to file

I want to write data from API to file, but i get weird characters written to file instead of string

import requests
end_url = url `+ "?key=" + api_key + "&lang=en-ru" + "&text=" + "Hello 
world"
response = requests.get(end_url)   
str = response.json()["text"][0]   
print(type(str)) # class 'str'   
print(str) # string that i want to write to file   
file = open("translate.txt", 'r+')   
file.write(str)

It should write string which i get from API to file, but it writes this: �����`

Upvotes: 1

Views: 50

Answers (1)

LowRezCat
LowRezCat

Reputation: 46

Try encoding flag in open function

import requests

end_url = url `+ "?key=" + api_key + "&lang=en-ru" + "&text=" + "Hello world"

response = requests.get(end_url)   
str = response.json()["text"][0]   

print(type(str)) # class 'str'   
print(str) # string that i want to write to file   

file = open("translate.txt", 'r+', encoding='utf-8')   
file.write(str)

Basically encoding is the way for computer to store text in files

If you want to know more about UTF-8

Upvotes: 0

Related Questions