简体   繁体   English

在新行上写入文本文件

[英]Writing on new lines to a text file

The section of coding I've written is as such: 我写的编码部分是这样的:

thing=9
text_file=open("something.txt", "a")
text_file.write("\n", str(thing))
text_file.close()

This always returns the error Type error: "write" only takes 1 argument. 这总是返回错误Type错误:“ write”仅接受1个参数。 2 given. 2给。 What I'm trying to do is that each time I run this code it writes on a new line rather than the same line. 我想做的是,每次我运行这段代码时,它都会写在新行而不是同一行。 Right now, if this doesn't work, I'm a bit confused how to do this. 现在,如果这行不通,我有点困惑该怎么做。 Any help would be appreciated! 任何帮助,将不胜感激!

The python interpreter is correct in saying: python解释器正确地说:

"write" only takes 1 argument. 2 given

Python's file methods are documented here . 此处记录 Python的文件方法。

All you need to be doing is concatenating your string with the newline character. 您需要做的只是将字符串与换行符连接在一起。 You can do so by replacing: 您可以这样替换:

text_file.write("\n", str(thing))

with: 与:

text_file.write("\n" + str(thing))

This will write an empty line before writing out what you want. 这将在写出所需内容之前写一个空行。 This might not be what you are looking for. 这可能不是您想要的。 Instead you can do: 相反,您可以执行以下操作:

text_file.write(str(thing) + '\n')

Add a newline to the end 1 of the string with the + operator: 使用+运算符将换行符添加到字符串的末尾1

text_file.write(str(thing) + "\n")

1 Note: If you add it to the front, you will get a blank line at the top of your file, which may not be what you want. 1注意:如果将其添加到最前面,则文件顶部将出现空白行,而这可能不是您想要的。

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

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