【问题标题】:How to append data to text file in python 2.7.11?如何在 python 2.7.11 中将数据附加到文本文件?
【发布时间】:2016-06-13 21:04:15
【问题描述】:

谁能告诉我如何在文本文件的新行中添加超链接?如果文本文件的第一行中已经有数据,我希望将数据插入下一个空行。我正在编写多个指向文本文件的超链接(附加)。提前致谢。

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

【问题讨论】:

  • my_file = open('file.txt', 'a+'); my_file.write(my_string); ? (这会覆盖,但你尝试过使用 file/write 吗?)
  • 感谢您的回复。我试过了,但它把所有 my_string 一个接一个地写在一行中。有没有办法在多次调用时将每个 my_string 写在单独的行中?
  • 您可以将每个字符串存储在一个列表(等等)中,然后在for 循环中遍历该列表。在您编写的每个字符串的末尾,确保附加一个换行符(即\n。)
  • 感谢您解决了问题 :-)

标签: python string python-2.7 text file-io


【解决方案1】:

看看pythondocs

您可以使用with open 语句打开文件。

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

【讨论】:

    【解决方案2】:

    您可以将要写入文件的字符串收集在一个列表(等)中,然后使用python内置的文件操作,即open(&lt;file&gt;)&lt;file&gt;.write(&lt;string&gt;),例如:

    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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 2021-12-15
      • 2015-02-04
      • 2011-01-24
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多