2016-06-13 120 views
1

任何人都可以告訴我如何添加超鏈接到文本文件中的新行?如果在第一行文本文件中已經有數據,我想將數據插入到下一個空行。我正在寫多個超鏈接到文本文件(追加)。提前致謝。如何將數據追加到Python 2.7.11中的文本文件?

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

'my_file = open('file.txt','a +'); my_file.write(my_string);'? (這會覆蓋,但你有沒有嘗試過使用文件/寫入?) –

+0

感謝您的回覆。我試過了,但是它把所有的my_string都寫在一行之後。有沒有辦法在多次調用時在sperate行中寫入每個my_string? – user1788736

+1

您可以將每個字符串存儲在列表中(等),然後在'for'循環中遍歷列表。在你寫的每一個字符串的末尾,確保附加了一個換行符(即'\ n')。 –

回答

4

看看python docs

您可以使用with open語句來打開文件。

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

您可以收集要寫入到文件列表中(等),然後使用Python的字符串內置的文件操作,即open(<file>)<file>.write(<string>),因爲這樣的:

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

另請參閱:How do you append to a file?