[英]I cant figure out how to write this list to a csv file how i want it, python
This is my code: 这是我的代码:
geometries = [[a, b, c], [d, e, f]] #Note I have lists within a list, this is required
with open("./datafiles/" + name, 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
writer.writerow(geometries)
This code is meant to write the lists within geometries to a CSV file. 此代码旨在将几何图形中的列表写入CSV文件。 The CSV file should look like this: CSV文件应如下所示:
a, b, c
d, e, f
Instead I get a txt file that looks like this: 相反,我得到一个看起来像这样的txt文件:
|['a', 'b', 'c']|,|['d','e','f']|
How do I remove these ( | [ ] '' ) from the text file and have it displayed as above? 如何从文本文件中删除这些(| []'')并使其如上显示?
You want to use .writerows()
not writerow()
. 您要使用.writerows()
而不是writerow()
。
By using the correct function, it'll output your CSV file as you expect. 使用正确的功能,它将按预期输出CSV文件。
The issue you have with the lines showing on the same row in some editors is due to your lineterminator
. 在某些编辑器中,同一行上显示的行存在问题,这是由于您的lineterminator
行器引起的。 You are setting it to \\n
, instead of the default \\r\\n
您将其设置为\\n
,而不是默认的\\r\\n
.writerow()
expects a flat list as a parameter. .writerow()
需要一个平面列表作为参数。 To write a list of rows at once use .writerows()
: 要一次写入行列表,请使用.writerows()
:
geometries = [[a, b, c], [d, e, f]]
with open("./datafiles/" + name, 'wb') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='|',
quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
writer.writerows(geometries)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.