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

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

问题描述

从其他帖子中,我了解到\n"在添加到 txt 文件时表示换行.我正在尝试这样做,但是当属性正好位于新行之前时,我无法弄清楚正确的语法.

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天全站免登陆