[英]How to split() each entry in a list into a new csv column
I have the following code which is reading a list of folders from a directory, and dumping them into a csv file. 我有以下代码,该代码从目录中读取文件夹列表,并将其转储到csv文件中。
import os, csv
mylist = os.listdir("M:/")
with open("output.csv", 'w') as myfile:
wr = csv.writer(myfile, lineterminator='\n')
wr.writerows(([row] for row in mylist))
Which is working well. 哪个运作良好。 The folders in the directory are all named using this format:
目录中的文件夹均使用以下格式命名:
abc_123456
And the output I'm trying to get is: 我想要得到的输出是:
abc, 123456
def, 789012
etc. 等等
I know that I need to use split() but I can't work out where it needs to go 我知道我需要使用split()但我无法解决它需要去的地方
Assuming row = "abc_123456"
, you need to split that on "_"
假设
row = "abc_123456"
,则需要在"_"
上拆分
[row]
is making a list of one string that you are writing as the row. [row]
列出了要作为行写入的一个字符串的列表。
row.split("_")
is how you would split the data. row.split("_")
是分割数据的方式。 This returns a list already, so no need for [row.split("_")]
, for example 这已经返回一个列表,因此不需要
[row.split("_")]
,例如
If you want to have ", "
as the delimiter rather than only a comma, then you need to add that to the writer. 如果要使用
", "
作为分隔符而不是仅使用逗号,则需要将其添加到编写器中。
wr = csv.writer(myfile, delimiter=', ', lineterminator='\n')
wr.writerows(row.split('_') for row in mylist)
As @OzgurVatansever stated in the comment you can simply split on "_"
: 正如@OzgurVatansever在评论中指出的,您可以简单地在
"_"
上分割:
import os, csv
mylist = os.listdir("M:/")
with open("output.csv", 'w') as myfile:
wr = csv.writer(myfile, lineterminator='\n')
wr.writerows(row.split("_") for row in mylist)
Hope that helps. 希望能有所帮助。 Thanks @OzgurVatansever.
谢谢@OzgurVatansever。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.