简体   繁体   中英

How do i make the data on my 2nd loop save in another row in csv

This is the function that i want to run but what happened is that the 2nd loop of data replaces the first loop of data that was saved in the csv
class Search():

def searchtest(self):

    # print(soup)

    test_words = ['abad','abercrombie']
    full_name = ['Abad, Christina Q.','Abercrombie, Veronica F.']
    test_word = ['STEVEN']
    x = 0



    for i in test_words:
            print("------------")  
            search = self.driver.find_element_by_xpath('//*[@id="page-wrapper"]/div[3]/div/div/div/div/div[3]/tabletoolstrans/div/input')
            search.clear()
            search.send_keys(i)
            search.send_keys(Keys.RETURN)
            time.sleep(3)
            soup = BeautifulSoup(self.driver.page_source,"html.parser")
            for item in soup.findAll("tr", {"class": "hand_cursor ng-scope"}):
                for td in item.findAll("td")[1]:
                        name = full_name[x]
                        print(name)
                        if td == name:
                            print("Search :"+name+"")
                            print("Pass")
                            buttons.save_csv(self, name, "Pass")
                        else:
                            print("Search :"+name+"")
                            buttons.save_csv(self, name, "Fail")
            x += 1
            print("<------------>")
    time.sleep(3)

This is the csv function that prints the data into the excel def save_csv(self, name, a):

    with open('test_case.xlsx','w', newline='') as csvfile:
        obj = csv.writer(csvfile, delimiter='\t',)
        obj.writerow([name,a])

    csvfile.close()

Expected Result Abad, Christina Q. |Pass Abercrombie, Veronica F. |Pass

Try opening the file you're writing to in append mode rather than write mode.

In your save_csv function, with open('test_case.xlsx','w', newline='')... will overwrite the file if it already exists. To add onto an existing file, you want with open('test_case.xlsx','a', newline='')... .

Reference: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM