如何在Python 3中写入.txt文件 [英] How to write to .txt files in Python 3

查看:77
本文介绍了如何在Python 3中写入.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与此.py文件相同的文件夹中有一个.txt文件,并且文件中包含以下文件:

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

如何将var(var ='ant')保存到.txt文件的下一行?

How can I save a var (var = 'ant') to the next line of the .txt file?

推荐答案

以附加模式打开文件并编写新行(包括\n行分隔符):

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.

这篇关于如何在Python 3中写入.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆