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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20429246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:25:09  来源:igfitidea点击:

How to write to .txt files in Python 3

pythonfiletextfile-io

提问by Toby Smith

I have a .txtfile in the same folder as this .pyfile and it has this in it:

.txt在与此.py文件相同的文件夹中有一个文件,其中包含以下内容:

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

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

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

采纳答案by Martijn Pieters

Open the file in append mode and write a new line (including a \nline 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.

这会在文件末尾添加所有其他内容之后的行。

回答by Sebastian

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='')没有换行符)。