How to write to .txt files in Python 3

后端 未结 2 1472
庸人自扰
庸人自扰 2020-12-29 01:24

I have a .txt file in the same folder as this .py file and it has this in it:

cat\\n
dog\\n
rat\\n
cow\\n

How can

2条回答
  •  一个人的身影
    2020-12-29 02:13

    Open the file in append mode and write a new line (including a \n line separator):

    with open(filename, 'a') as out:
        out.write(var + '\n')
    

    This adds the line at the end of the file after all the other contents.

提交回复
热议问题