简体   繁体   English

我无法弄清楚如何将此列表写入csv文件,python

[英]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.

相关问题 二维列表函数,我不知道如何打印输入,python - 2d list functions, i cant figure out how to print input, python 大家好。 我想在 python 中为附加的数据框编写一个函数。 我不知道我该怎么做 - Hi everyone. I want to write a function in python for attached data frame. I can not figure out how can I do it 无法弄清楚如何在 selinium 中的 python 中编写 xpath - Cant figure out how to write xpath in python in selinium 我试图找出 .csv 文件的最大值和最小值,但我无法弄清楚我做错了什么 - Im trying to figure out the max and min of a .csv file and i cant figure out what im doing wrong 我正在做一个项目,我只想在被要求时运行另一个 python 文件,但我无法弄清楚代码 - I am working on a project and I want to run another python file only when asked to but I cant figure out the code 我无法弄清楚如何在scrapinghub部署中使用csv文件进行列表理解 - I cannot figure out how to use a csv file for a list comprehension in scrapinghub deployment 我想弄清楚怎么做 - I want to figure out how to make t 如何将Python列表写到文件中? - How do I write a Python list out to a file? IndexError:列表索引超出范围。 我不知道如何摆脱它 - IndexError: list index out of range. I cant figure out how to get rid of it 每次我在命令中输入视图时,我都无法弄清楚如何让它不说添加视图到列表中 - I cant figure out how to make it not say added view to list every time i type view into the command
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM