0

I have the following code which is reading a list of folders from a directory, and dumping them into a csv file.

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

Mcam435
  • 101
  • 2
  • 13

2 Answers2

3

Assuming row = "abc_123456", you need to split that on "_"

[row] is making a list of one string that you are writing as the row.

row.split("_") is how you would split the data. This returns a list already, so no need for [row.split("_")], for example

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)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
2

As @OzgurVatansever stated in the comment you can simply split on "_":

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.

Cyzanfar
  • 6,997
  • 9
  • 43
  • 81