Home > Enterprise >  How to write on new line in txt. file
How to write on new line in txt. file

Time:07-24

How come that 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"))

CodePudding user response:

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