简体   繁体   中英

How to write on new line in txt. file

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"))

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"))

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"))
        

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