[英]Python: Saving to CSV file, accidentally writing to next column instead of row after manually opening the file
I've noticed a really weird bug and didn't know if anyone else had seen this / knows how to stop it.我注意到一个非常奇怪的错误,不知道是否有其他人看到过这个/知道如何阻止它。
I'm writing to a CSV file using this:我正在使用此写入 CSV 文件:
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])
and then write to the file:然后写入文件:
self.write_to_csv_file(self.result['outputLabel'], string)
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).如果我打开 CSV 文件查看结果,下次我写入文件时,它将从最后一行的第 3 列开始(第 1 列是对象,第 2 列是字符串)。
If I run self.write_to_csv_file(self.result['outputLabel'], string)
multiple times without manually opening the file (obviously I open the file in the Python script), everything is fine.如果我
self.write_to_csv_file(self.result['outputLabel'], string)
运行self.write_to_csv_file(self.result['outputLabel'], string)
而不手动打开文件(显然我在 Python 脚本中打开文件),一切都很好。
It's only when I open the file so I get the issue of starting on Column 3.只有当我打开文件时才会出现从第 3 列开始的问题。
Any thoughts on how to fix this?关于如何解决这个问题的任何想法?
You're opening the file in a ppend mode , so the data is appended to the end of the file.您以ppend模式打开文件,因此数据将附加到文件末尾。 If the file doesn't end in a newline, rows may get concatenated.
如果文件不以换行符结尾,则行可能会连接在一起。 Try writing a newline to the file before appending new rows:
在追加新行之前尝试向文件写入换行符:
with open("data_model_1.csv", "a") as f:
f.write("\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.