Open roberthsu2003 opened 1 month ago
import requests
url='https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
response=requests.get(url)
import os
import csv
from pprint import pprint
from os.path import dirname,join,abspath
file_path:str=join(dirname(abspath(__name__)),"data","各國gdp指數.csv")
file_path
print(type(response))
pprint(response.content) #.content 不會有\n
a=str(response.content)
with open(file_path,mode='w',newline='') as file:
file.write(a)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv")
gdp_data = df[['country', 'year', 'gdpPercap']]
gdp_pivot = gdp_data.pivot(index='country', columns='year', values='gdpPercap')
gdp_pivot.to_csv("各國GDP指數.csv")
print("檔案已存檔")
import requests
import os
import csv
url = "https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv"
response = requests.get(url)
if response.status_code == 200:
file_path = os.path.join("data", "各國gdp指數.csv")
with open(file_path,mode = "w",encoding = 'utf-8') as file:
file.write(response.text)
print(f"檔案已存在 {file_path}")
with open(file_path,encoding = 'utf-8',newline = '') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
else:
print("無法連線")
import pandas as pd
df = pd.read_csv("各國GDP指數.csv")
print(df)
import requests
import csv
import os
def get_data(url):
try:
response = requests.get(url)
except Exception as error:
print(error)
return error
else:
return response
def save_data(data,name):
file_path= os.path.abspath(__name__)
current_dir_name=os.path.dirname(file_path)
file_position=os.path.join(current_dir_name,'data',name)
with open(file_position,mode='w',newline='') as file:
writer = csv.DictWriter(file,data)
writer.writeheader()
def main():
data = get_data("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv")
if isinstance(data,str):
print(data)
return
name = '各國gdp指數.csv'
save_data(data,name)
main()