user1788736
user1788736

Reputation: 2845

How to append data to text file in python 2.7.11?

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 />";

Upvotes: 1

Views: 17444

Answers (2)

Chris Sprague
Chris Sprague

Reputation: 740

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?

Upvotes: 1

megadarkfriend
megadarkfriend

Reputation: 373

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)

Upvotes: 4

Related Questions