I am working on an example but stuck with some points. I am a beginner for python and try to improve myself. I am trying to use openweather api and get some data from it and then write these data to a csv file. The aim of my code is input a txt file which contains city names, I want to get City name, Country code, lat long, Temperature, Wind speed, Wind direction. and then write them to a csv file. I can input the txt file or get the data with input from the command line but can not do both. And also I want to write the data to a csv file. Could you please help me? I can write it to the console, but I need to write them to the csv file. But, I can not convert my json object to csv
My input.txt
Los Angeles
San Francisco
...
My code:
import requests
from pprint import pprint
import csv
import pandas as pd
file = input("Input the filepath: ")
with open(file) as f:
for line in f:
line = line.strip()
API_key = "MYAPIKEY"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
headers = {'content-type': 'application/json'}
city_name = line
Final_url = base_url + "appid=" + API_key + "&q=" + city_name
weather_data = requests.get(Final_url).json()
print("\nCurrent Weather" + city_name + ":\n")
weather_data = requests.get(Final_url, headers=headers)
f = open('weather_data_file.csv', "w")
f.write(weather_data.text)
f.close()
print(f)
The problem after edit:
The CSV file just contains the last city data and data is not in a proper form if I open with excel
The data it outputs:
{"coord":{"lon":-122.42,"lat":37.77},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":284.74,"feels_like":280.59,"temp_min":283.15,"temp_max":286.48,"pressure":1024,"humidity":76},"visibility":10000,"wind":{"speed":5.1,"deg":260},"clouds":{"all":40},"dt":1609003065,"sys":{"type":1,"id":5817,"country":"US","sunrise":1608996226,"sunset":1609030632},"timezone":-28800,"id":5391959,"name":"San Francisco","cod":200}