[英]Python write () writing string onto new line?
I'm trying to get the below write to file() code to be written on one line in a txt file.我正在尝试将以下写入 file() 代码写入 txt 文件中的一行。
I want it to write all on one line: "Error can't parse str(line) to a float."我希望它全部写在一行上:“错误无法将 str(line) 解析为浮点数。” In a txt file.在一个 txt 文件中。
However the "to a float" always gets written on the line below the "Error can't parse str(line)".然而,“to a float”总是写在“Error can't parse str(line)”下面的行上。
I feel it has something to do with the + sign but if I take it away it gives and error code that write() can't pass 2 arguments.我觉得它与 + 号有关,但如果我把它拿走,它会给出 write() 无法通过 2 arguments 的错误代码。 Any suggestions?有什么建议么?
outputFile.write("Error can't parse " + str(line) + "to a float" + '\n')
Here is my result:这是我的结果:
Error can't parse str(line)错误无法解析 str(line)
to a float浮动
One problem is that your line
variable is a string containing \n
at the end.一个问题是您的line
变量是一个包含\n
结尾的字符串。
Use the following code instead:请改用以下代码:
print(
"Error can't parse",
str(line).strip(),
"to a float",
file=outputFile
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.