Как построчно сохранить список в файле xlsx file (excel) - PullRequest
0 голосов
/ 27 марта 2020

Я создаю код, который будет извлекать все подтвержденные выздоровления и смерти во всем мире. Я хочу, чтобы он был сохранен в файле xlsx (Line By Line), но весь учебник там не работал. это код, который я использую

from tkinter import *
from tkinter import messagebox
import COVID19Py
def confirmed_wrld():
    conf_list = covid19.getLocations(rank_by='confirmed')
    with open("confirmed.txt", 'w') as output:
        for row in conf_list:
            output.write(str(row) + '\n')
    messagebox.showinfo('Saved','The list is saved in confirmed.txt file in the same folder if you dont have confirmed.txt file create one in the same directory and redo this action')

def recovered_wrld():
    recovered_lst = covid19.getLocations(rank_by='recovered')
    with open("recovered.txt", 'w') as output:
        for row in recovered_lst:
            output.write(str(row) + '\n')
    messagebox.showinfo('Saved',"The list is saved in recovered.txt file in the same folder if you dont have recovered.txt file create one in the same directory and redo this action")

def deaths_wrld():
    dth_lst = covid19.getLocations(rank_by='deaths')
    messagebox.showinfo('Done', dth_lst)
    with open("deaths.txt", 'w') as output:
        for row in dth_lst:
            output.write(str(row) + '\n')
    messagebox.showinfo('Saved',"The list is saved in deaths.txt file in the same folder if you dont have deaths.txt file create one in the same directory and redo this action")
covid19 = COVID19Py.COVID19(data_source="csbs")
root = Tk()
root.geometry("500x500")
root.title("CoronaVirus Locator")
confirmed_BTN = Button(text="confirmed in the whole world", command = confirmed_wrld)
confirmed_BTN.pack()
recovered_BTN = Button(text="recovered in the whole world", command = recovered_wrld)
recovered_BTN.pack()
deaths_BTN = Button(text="deaths in the whole world", command = deaths_wrld)
deaths_BTN.pack()
root.mainloop()

, как вы можете видеть, я пытаюсь сохранить его как текстовый файл, он работает, но я хочу, чтобы он был в xlsx, чтобы другие люди могли легко его увидеть.

Ответы [ 2 ]

1 голос
/ 27 марта 2020

Сначала необходимо сгладить словари в dht_lst, затем вы можете использовать библиотеку pandas для сохранения списка flattened в виде файла excel.

Попробуйте это:

import pandas as pd
from pandas import ExcelWriter

def deaths_wrld():
    dth_lst = covid19.getLocations(rank_by='deaths')
    messagebox.showinfo('Done', dth_lst)

    flattened = pd.json_normalize(dht_lst)
    with ExcelWriter('excel_file.xlsx') as writer:
        pd.DataFrame(flattened).to_excel(writer, index=False)
        writer.save()

    messagebox.showinfo('Saved',"The list is saved in deaths.txt file in the same folder if you dont have deaths.txt file create one in the same directory and redo this action")

Вы можете установить pandas библиотеку, используя pip install pandas, вам также может понадобиться установить pip install openpyxl для поддержки Excel.

0 голосов
/ 27 марта 2020

Один простой способ, который я знаю, это преобразовать dict в dataframe, а затем сохранить в файл Excel.

, пожалуйста, установите pandas от pip install pandas

from tkinter import *
from tkinter import messagebox
import COVID19Py
import pandas as pd
def fight_corona(conf_list):
    d = pd.DataFrame.from_dict(conf_list)
    d = pd.concat([d, d['coordinates'].apply(pd.Series),d['latest'].apply(pd.Series)], axis=1)
    d.drop(columns= ['coordinates', 'latest'], inplace= True)
    return d
def confirmed_wrld():
    conf_list = covid19.getLocations(rank_by='confirmed')
    df = fight_corona(conf_list)
    df.to_excel('confirmed.xlsx')
    messagebox.showinfo('Saved','The list is saved in confirmed.txt file in the same folder if you dont have confirmed.txt file create one in the same directory and redo this action')

def recovered_wrld():
    conf_list= covid19.getLocations(rank_by='recovered')
    df = fight_corona(conf_list)
    df.to_excel('recovered.xlsx')
    messagebox.showinfo('Saved',"The list is saved in recovered.txt file in the same folder if you dont have recovered.txt file create one in the same directory and redo this action")

def deaths_wrld():
    conf_list= covid19.getLocations(rank_by='deaths')
    df = fight_corona(conf_list)
    df.to_excel('deaths.xlsx')
    messagebox.showinfo('Saved',"The list is saved in deaths.txt file in the same folder if you dont have deaths.txt file create one in the same directory and redo this action")
covid19 = COVID19Py.COVID19(data_source="csbs")
root = Tk()
root.geometry("500x500")
root.title("CoronaVirus Locator")
confirmed_BTN = Button(text="confirmed in the whole world", command = confirmed_wrld)
confirmed_BTN.pack()
recovered_BTN = Button(text="recovered in the whole world", command = recovered_wrld)
recovered_BTN.pack()
deaths_BTN = Button(text="deaths in the whole world", command = deaths_wrld)
deaths_BTN.pack()
root.mainloop()

Я проверил это код на windows 10, и он работает хорошо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...