How to write on new line in txt. file

Question:

How come this code only returns a single line in the .txt file? I want to write the value on a new line every time.

    find_href = driver.find_elements_by_css_selector('img.gs-image.gs-image-scalable')
    for my_href in find_href:
        with open("txt.txt", "w") as textFile:
            textFile.writelines(str(my_href.get_attribute("src")))
        print(my_href.get_attribute("src"))
Asked By: AnxiousLuna

||

Answers:

writelines() doesn’t add newlines. You need to concatenate the newline explicitly. Also, you just have a single string, so you shouldn’t be calling writelines(), which expects a list of lines to write. Use write() to write a single string.

Also, you should just open the file once before the loop, not each time through the loop. You keep overwriting the file rather than appending to it.

ind_href = driver.find_elements_by_css_selector('img.gs-image.gs-image-scalable')
with open("txt.txt", "w") as textFile:
    for my_href in find_href:
        textFile.write(str(my_href.get_attribute("src")) + "n")
    print(my_href.get_attribute("src"))
Answered By: Barmar

Update solution would be :

find_href = driver.find_elements(By.CSS_SELECTOR, 'img.gs-image.gs-image-scalable')
with open("txt.txt", "w") as textFile:
    for my_href in find_href:
        textFile.write(str(my_href.get_attribute("src")) + "n")
    print(my_href.get_attribute("src"))
        
Answered By: AnxiousLuna
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.