简体   繁体   English

如何在python中将变量写入文本文件中的新行

[英]How to write variables to a new line in a text file in python

Here is my code: 这是我的代码:

f = open("text.txt", "w+")
var2 = input()
f.write(var2'\n')

How can I make this work? 我该如何进行这项工作?

This should work 这应该工作

f = open("text.txt", "w+")
var2 = input()
f.write(var2 + '\n')
f.close()

But, this is a better way to do it 但是,这是一种更好的方法

with open("text.txt", "w+") as f:
    f.write(var2 + '\n')

if var is a string, you can just do f.write(var + '\\n') . 如果var是一个字符串,则可以执行f.write(var + '\\n') If var is not a string, you will need to do f.write(str(var) + '\\n') 如果var不是字符串,则需要执行f.write(str(var) + '\\n')

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

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