import requests import csv url = 'https://steamwebapi.com/steam/api/items' params = {…
- User
import requests import csv
url = 'https://steamwebapi.com/steam/api/items' params = { 'game': 'csgo', 'key': 'UVCGXSS0FNPA5ICT' }
response = requests.get(url, params=params)
Save the data to a csv file
file_path = 'steam_items.csv'
with open(file_path, mode='w', newline='') as file: writer = csv.writer(file) writer.writerow(['id', 'name', 'type', 'icon_url']) data = response.json() for item in data: writer.writerow([item['marketHashName'], item['type'], item['wear'], item['priceAvg'], item['priceSafeTs24H'], item['sold24H']])
print('Done!')
this is my python code getting this error
Traceback (most recent call last): File "c:\Users\ericv\Desktop\TDB\test.py", line 20, in writer.writerow([item['marketHashName'], item['type'], item['wear'], item['priceAvg'], item['priceSafeTs24H'], item['sold24H']]) File "C:\Users\ericv\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2605' in position 0: character maps to
- Assistant
The issue is with the character encoding when writing data to the csv file. The default encoding
cp1252is unable to encode the special character\u2605. To fix this, you need to explicitly specify the encoding asutf-8when opening the file. Here's the modified code:pythonimport requests import csv url = 'https://steamwebapi.com/steam/api/items' params = { 'game': 'csgo', 'key': 'UVCGXSS0FNPA5ICT' } response = requests.get(url, params=params) # Save the data to a csv file file_path = 'steam_items.csv' with open(file_path, mode='w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['id', 'name', 'type', 'icon_url']) data = response.json() for item in data: writer.writerow([item['marketHashName'], item['type'], item['wear'], item['priceAvg'], item['priceSafeTs24H'], item['sold24H']]) print('Done!')