【问题标题】:Appending variable to end of file on a newline in Python在 Python 中的换行符上将变量附加到文件末尾
【发布时间】:2020-08-25 01:39:06
【问题描述】:

我正在尝试将变量中的数据附加到 Python 文件的末尾 - 在新行上。我使用了这种方法:(variable+"/n"),但在文件中,它在一行中包含所有文件数据,包括/n 符号。

我的代码(这是一个例子!所以这正是我想要回答的内容)

list = ["apple","pear","strawberry"]
f = open("test.txt","a")
for x in list:
    f.write(x+"/n")
    print(x)
f.close()

test.txt 中的输出:

apple/npear/nstrawberry/n

我该怎么做才能使输出看起来像这样:

apple
pear
strawberry

提前感谢您的回答!

【问题讨论】:

  • "/n" != "\n"...

标签: python file append


【解决方案1】:

将正斜杠 (/) 替换为反斜杠 ()。

代码:

list = ["apple","pear","strawberry"]
f = open("test.txt","a")
for x in list:
    f.write(x+"\n")
    print(x)
f.close()

【讨论】:

    【解决方案2】:

    在第 5 行尝试使用 \n 而不是 /n。

    【讨论】:

      【解决方案3】:

      以下代码正常工作

      list = ["apple","pear","strawberry"]
          f = open("test.txt","a")
          for x in list:
            f.write(x)
            print(x, end='/n')
          f.close()
      

      输出:

      apple/npear/nstrawberry/n
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-26
        • 2014-08-04
        • 2013-11-15
        • 2013-08-24
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多