Home > front end >  python how to clear items from list after complete each loop?
python how to clear items from list after complete each loop?

Time:09-17

I am using list for store all image urls from each product but my list adding previous image url in every new product. I want to clear list after write my csv and complete each loop. here is my code:

image_list = []

for page_num in range(1,6):
    ....my others code

   

            try:
                
                images = driver.find_elements_by_xpath("//img[@class='Image--fadeIn lazyautosizes Image--lazyLoaded']")
                for i in images:
                    image = i.get_attribute('data-original-src')
                    image_list.append("https:" image)
                    print('######image: ',image)
            except:
                images = driver.find_element_by_css_selector("#shopify-section-product-template .Image--lazyLoaded")
                image = i.get_attribute('data-original-src')
                image_list.append("https:" image)
                print(image)

            with open("product.csv", "a",encoding="utf-8") as f:
                            writeFile = csv.writer(f)
                            writeFile.writerow([image_list])

CodePudding user response:

assign it to empty list

image_list = []

or use google for 5 seconds

image_list.clear()

CodePudding user response:

You can clear the image_list list with

image_list = []

or

image_list = list()

After writing the list content into the CSV file.
So your entire code can be as following:

image_list = []

for page_num in range(1,6):
    ....my others code

   

            try:
                
                images = driver.find_elements_by_xpath("//img[@class='Image--fadeIn lazyautosizes Image--lazyLoaded']")
                for i in images:
                    image = i.get_attribute('data-original-src')
                    image_list.append("https:" image)
                    print('######image: ',image)
            except:
                images = driver.find_element_by_css_selector("#shopify-section-product-template .Image--lazyLoaded")
                image = i.get_attribute('data-original-src')
                image_list.append("https:" image)
                print(image)

            with open("product.csv", "a",encoding="utf-8") as f:
                            writeFile = csv.writer(f)
                            writeFile.writerow([image_list])
            image_list = []
  • Related