1

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 />";
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
user1788736
  • 2,727
  • 20
  • 66
  • 110
  • 1
    `my_file = open('file.txt', 'a+'); my_file.write(my_string);` ? (this will overwrite, but have you tried using file/write yet?) – Chris Sprague Jun 13 '16 at 21:08
  • Thanks for replyes. I tried it but it writes all the my_string in one line after each other . Is there a way to write each my_string in sperate line when multiple time it is called ? – user1788736 Jun 13 '16 at 21:18
  • 1
    You could have each string stored in a list (etc.) and then iterate over the list in a `for` loop. At the end of each string you write, make sure a newline is appended (i.e. `\n`.) – Chris Sprague Jun 13 '16 at 21:23
  • Thanks that fixed the problem :-) – user1788736 Jun 13 '16 at 21:28
  • 1
    Possible duplicate of [How do you append to a file?](https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file) – rkersh Dec 05 '17 at 00:30

2 Answers2

4

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)
megadarkfriend
  • 373
  • 1
  • 16
1

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?

Community
  • 1
  • 1
Chris Sprague
  • 740
  • 1
  • 12
  • 22