简体   繁体   English

如何在 Python 3 中写入 .txt 文件

[英]How to write to .txt files in Python 3

I have a .txt file in the same folder as this .py file and it has this in it:我在与此.py文件相同的文件夹中有一个.txt文件,其中包含以下内容:

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

How can I save a var (var = 'ant') to the next line of the .txt file?如何将 var (var = 'ant') 保存到.txt文件的下一行?

Open the file in append mode and write a new line (including a \\n line separator):以追加模式打开文件并写入一个新行(包括\\n行分隔符):

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.这会在文件末尾添加所有其他内容之后的行。

Just to be complete on this question:只是为了完成这个问题:

You can also use the print function .您还可以使用打印功能

with open(filename, 'a') as f:
    print(var, file=f)

The print function will automatically end each print with a newline (unless given an alternative ending in the call, for example print(var, file=f, end='') for no newlines).打印函数将自动以换行符结束每次打印(除非在调用中给出替代结尾,例如print(var, file=f, end='')表示没有换行符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM