Python: Saving to CSV file, accidentally writing to next column instead of row after manually opening the file
<p>I've noticed a really weird bug and didn't know if anyone else had seen this / knows how to stop it. </p>

<p>I'm writing to a CSV file using this:</p>

<pre><code>def write_to_csv_file(self, object, string):
        with open('data_model_1.csv', 'a') as f:
            writer = csv.writer(f)
            writer.writerow([object, string])
</code></pre>

<p>and then write to the file:</p>

<pre><code>self.write_to_csv_file(self.result['outputLabel'], string)
</code></pre>

<p>If I open the CSV file to look at the results, the next time I write to the file, it will start in column 3 of the last line (column 1 is object, column 2 is string).</p>

<p>If I run <code>self.write_to_csv_file(self.result['outputLabel'], string)</code> multiple times without manually opening the file (obviously I open the file in the Python script), everything is fine. </p>

<p>It's only when I open the file so I get the issue of starting on Column 3. </p>

<p>Any thoughts on how to fix this?</p>

<p>You're opening the file in <strong>a</strong>ppend <a href="https://docs.python.org/3.6/library/functions.html#open" rel="nofollow">mode</a>, so the data is appended to the end of the file. If the file doesn't end in a newline, rows may get concatenated. Try writing a newline to the file before appending new rows:</p>

<pre><code>with open("data_model_1.csv", "a") as f:
    f.write("\n")
</code></pre>

python csv