Reputation: 547
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
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