简体   繁体   English

如何使用 python 将具有多行的字符串写入文件

[英]How to write a string with mutiple lines into file with python

for j in search(query, tld="co.in", num=10, stop=10, pause=5):
    print(j)
f.writelines(j)

i have been trying write J to a text file but it only gives me the 10th url and omits the first nine this is the first time Ive ever been truly stumped can anyone help?我一直在尝试将 J 写入文本文件,但它只给了我第 10 个 url 并省略了前 9 个,这是我第一次真正被难住了,谁能帮忙? for context im using python to search and log google searches and it outputs like url1 \n url2 \n url3 \n url4 \n url5 \n url6 \n url7 \n url8 \n url9 \n url10 and thats fine but when i try to write it to a file it only writes url 10对于上下文我使用 python 搜索和记录谷歌搜索,它输出像 url1 \n url2 \n url3 \n url4 \n url5 \n url6 \n url7 \n url8 \n url9 \n url10 这很好但是当我尝试将其写入文件,它只写入 url 10

The screaming issue here is that f.writelines(j) is outside the loop (If that wasn't just a typo on the post, of course).这里的尖叫问题是 f.writelines(j) 在循环之外(当然,如果这不仅仅是帖子上的错字)。 Also, I see no point in using writelines when you're passing a single string.另外,当您传递单个字符串时,我认为使用 writelines 没有任何意义。

for j in search(query, tld="co.in", num=10, stop=10, pause=5):
    print(j)
    f.write(j + '\n')

Does this make any difference?这有什么区别吗?

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

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