简体   繁体   English

如何将列表中的每个条目拆分()成新的CSV列

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

相关问题 我如何在前两个空格处拆分每个列表条目并将其全部添加到新列表中 - how can i split each list entry at the first two spaces and add them all into a new list 如何将 append 列表每次添加到 CSV 文件的新列? - How to append a list each time to a new column of a CSV file? 如何拆分推文的文本部分,以使文本的每个单词在CSV文件的新列中 - How do i split the text part of a tweet to have each word of the text in a new column in a CSV file 如何拆分一列但保留每个条目的键? - How do I split out a column but keep the key for each entry? 当每个列表可能具有不同数量的成员时,如何将列表中的一列拆分为新列? - How to split one column in a list into new columns when each list may have different number of members? 如何将用户输入的整数拆分为一个列表,其中每个条目为 2 位数字? - How to split user input integer into a list, where each entry is 2 digits? 使用python在空间上拆分csv列条目 - split csv column entry on space using python 将每个字典值与 csv 列条目匹配并将字典键应用于新列 - Match each dictionary value with csv column entry and apply dictionary key to new column Pandas - 拆分列条目(彼此分隔符) - Pandas - Split column entry (each other seperator) 如何在Python中将列中的每个值拆分为单独的CSV文件? - How to split each value in a column as a seperate csv file in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM