How to append data to text file in python 2.7.11?

别等时光非礼了梦想. 提交于 2019-12-24 09:33:20

问题


Could any one show me how i can add hyperlinks to new line in text file? If there is already data in first line of text file i want the data get inserted in the next empty line. I am writing multiple hyperlinks to text file(append). Thanks in advance.

    print "<a href=\"http://somewebsite.com/test.php?Id="+str(val)+"&m3u8="+lyrics+"&title=test\">"+str(i)+ "</a> <br />";

回答1:


Take a look at the python docs.

You can use the with open statement to open the file.

with open(filename, 'a') as f:
    f.write(text)



回答2:


You can collect the strings you want to write to the file in a list (etc.) and then use python's built-in file operations, namely open(<file>) and <file>.write(<string>), as such:

strings = ['hello', 'world', 'today']

# Open the file for (a)ppending, (+) creating it if it didn't exist
f = open('file.txt', 'a+')

for s in strings:
    f.write(s + "\n")

See also: How do you append to a file?



来源:https://stackoverflow.com/questions/37799078/how-to-append-data-to-text-file-in-python-2-7-11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!