繁体   English   中英

如何在txt中换行。 文件

[英]How to write on new line in txt. file

为什么这段代码只返回 .txt 文件中的一行? 我想每次都在新行上写下这个值。

    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()不添加换行符。 您需要明确地连接换行符。 此外,您只有一个字符串,因此您不应该调用writelines() ,它需要写入行列表。 使用write()写入单个字符串。

此外,您应该只在循环之前打开文件一次,而不是每次都通过循环。 您继续覆盖文件而不是附加到它。

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

更新解决方案是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM