Domanda

I have a file already wrote ("file_wrote") at example:

1, 1, 1, 1, 1, 1
2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3

When I wish to write a line:

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)

I got this problem:

1, 1, 1, 1, 1, 1
2, 2, 2, 2, 2, 2
3, 3, 3, 3, 3, 3, a, a, a, a, a, a
È stato utile?

Soluzione

You need to add a newline to the front of newline:

file_out.write("\n" + newline)

Otherwise, Python will write the text to the end of the last line in the file.


Keep in mind too that you added a newline to the end of newline here:

newline = "    ".join([str(e) for e in line]) + "\n"
#                                               ^^^^

This means that, when you run your code, a blank line will be added to the end of the file. I think you might want to remove this newline:

newline = "    ".join([str(e) for e in line])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top