簡體   English   中英

如何在python 2.7.11中將數據追加到文本文件?

[英]How to append data to text file in python 2.7.11?

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

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

看看python docs

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

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

您可以在列表(等)中收集要寫入文件的字符串,然后使用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")

另請參閱: 如何附加到文件?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM