Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write on new line in txt. file

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading