我已经写了一个文件(" file_wrote"),例如:
1, 1, 1, 1, 1, 1
2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3
当我想写一行时:
line = ["a","a","a","a","a","a"]
newline = " ".join([str(e) for e in line]) + "\n"
with open("file_wrote", 'a') as file_out:
file_out.write(newline)
我遇到了这个问题:
1, 1, 1, 1, 1, 1
2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3, a, a, a, a, a, a
答案 0 :(得分:2)
您需要在newline
:
file_out.write("\n" + newline)
否则,Python会将文本写入文件中最后一行的末尾。
请注意,您在此处newline
的末尾添加了换行符:
newline = " ".join([str(e) for e in line]) + "\n"
# ^^^^
这意味着,当您运行代码时,将在文件末尾添加一个空行。我想你可能想要删除这个换行符:
newline = " ".join([str(e) for e in line])