Home > Net >  How to Stop Override data in Excel by Python
How to Stop Override data in Excel by Python

Time:03-02

I am saving data in an excel file, but it overrides the data and previous data loss, whenever I run the program again. I want to save data under the previous data every time whenever I run the program. sorry for the whole code because I don't which part of the code I should share with you. help, please!

//Python Code

from time import time
from turtle import heading, title
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter

# links in array of cardano only
links = ["https://cardanoscan.io/pool/eff96bfccda465d5be2c42e97ab4c6013bd08b29bd8a41feafcd4713", "https://cardanoscan.io/pool/54ee46b05aac43c6f692963d731037b1747a4cebfc119ccd2c5ad78b", "https://cardanoscan.io/pool/c44a041de1e1e85d5f89a5afac6d3c304e411855b2418ae209178cdc", "https://cardanoscan.io/pool/1f79d3dd8366a9d04512e59e3cd65c1342eaa261b641ef93e5ac8f86",
         "https://cardanoscan.io/pool/37776026d64eeb9fb5873caedc6e9c140f66c43ef6b3e396e061c891", "https://cardanoscan.io/pool/51897956cbe5c8f4751953c31ce85a1c60f5f27efee16397e6654947", "https://cardanoscan.io/pool/27ef7af15a7b854508385bf193acd73f7fb78b72ea6a99e8a413ca68", "https://cardanoscan.io/pool/b1b2d76b11afa2fbc6b5f89f078b47a9defa00707975f3fd4ebe1df2", "https://cardanoscan.io/pool/9390bd2c8d16935b3bdfeaae6301c203f67806511e492e3cf3dbfc69"]
print("Searching for Alerts!")
# loop to check alerts in website
wb = Workbook()
ws = wb.active
ws.title = "Links Alerts"

# Data Headings
headings = ['Branch Name', 'Branch Link', 'Threshold', 'Percentage', 'Status']
ws.append(headings)
#  making bold headings
for col in range(1, 6):
    ws[get_column_letter(col)   '1'].font = Font(bold=True)

# creating the main function to check alerts


def find_alerts():
    for link in links:  # searching link in lines one by one
        # request to get link data in text form
        html_text = requests.get(link).text
        # BeautifulSoup fromating the data for us
        soup = BeautifulSoup(html_text, "lxml")
        soup.prettify
        result = soup.find(
            'div', class_='position-absolute font-weight-bold').text.replace(' ', '')  # target the class where the data lies
        if "0%" not in result:  # condition for change
            ws.append(["Cardano", link, "Saturation",
                      result, "Issue found"])  # creating row if the condition execute
            print(
                f"Issue found in link: {link} because of {result} saturation.")
        else:
            ws.append(["Cardano", link, "Saturation",
                      result, " No Issue found"])  # same thing as above
            print("no Issue in this link!")
        ws.insert_rows(11)  # making space for new data
        wb.save('Alert_Checking.xlsx')  # saving file


if __name__ == '__main__':
    while True:
        find_alerts()  # calling the function
        time_wait = 60  # setting time
        print("  ")
        print(f"Wating for {time_wait} minutes to recheck again...")
        print(" ")
        input("Press Enter key to close the Tab!")
        time.sleep(time_wait * 60)

CodePudding user response:

You are creating a new workbook every time you run your script, so of course you won't retain data when running the script again. You can use a try ... except block to try and open the file, or create if it doesn't exist.

filename = "Alert_Checking.xlsx"
try:
    # File already exists, load file
    load_workbook(filename)
    ws = wb["Links Alerts"]
except FileNotFoundError:
    # File does not exist, create file
    wb = Workbook()
    ws = wb.active
    ws.title = "Links Alerts"

    # Data Headings
    headings = ['Branch Name', 'Branch Link', 'Threshold', 'Percentage', 'Status']
    ws.append(headings)
    #  making bold headings
    for col in range(1, 6):
        ws[get_column_letter(col)   '1'].font = Font(bold=True)
  • Related