在python中将变量写入txt文件的新行 [英] Writing variables to new line of txt file in python

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

问题描述

从其他帖子中,我了解到,添加到txt文件时, \n表示新行。我只是尝试这样做,但是当属性刚好在新行之前时,我无法找出正确的语法。

From other posts, I've learned that '\n' signifies a new line when adding to a txt file. I'm trying to do just this, but I can't figure out the right syntax when an attribute is right before the new line.

我正在尝试的代码如下:

My code I'm trying is like this:

for item in list:
    with open("file.txt", "w") as att_file:
        att_file.write(variable\n)

您可能会看到,我正在尝试将列表中每个项目的变量添加到txt文件的新行中。正确的方法是什么?

As you can probably see, I'm trying to add the variable for each item in the list to a new line in a txt file. What's the correct way to do this?

推荐答案

您只需将换行符指定为字符串:

You just need to specify the newline character as a string:

例如:

with open("file.txt", "w") as att_file:
    for item in list:
        att_file.write(attribute + "\n")

这篇关于在python中将变量写入txt文件的新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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