Python csv.writer delimiter with \ ?

4223
10
07-21-2016 12:39 PM
DevinUnderwood2
Occasional Contributor

How do I use a back slash as a delimiter, python wont recognize it.

ofile  = open('MapServicesInfo.csv', "w")

writer = csv.writer(ofile, delimiter = '\', quotechar='"', quoting=csv.QUOTE_ALL)

Tags (2)
0 Kudos
10 Replies
WesMiller
Regular Contributor III

In python a backslash is an escape character. I don't think you'll be able to use for a csv. Have you tried using 2 \\ or a forward / slash?

DevinUnderwood2
Occasional Contributor

This is an example of a row I need to write to csv file by delimiting the slash.

Write each section within the slashes to separate rows .

I guess I need to know how to make it not recognize as a escape character ?

... \Sewer\ControlValve  

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

Here is the process

>>> a = "Sewer\ControlValve"

>>> b = a.split("\\")

>>> b

['Sewer', 'ControlValve']

>>> c = ("{}\n"*len(b)).format(*b)

>>> c

'Sewer\nControlValve\n'

>>> print(c)

Sewer

ControlValve

Now that can be simplified of course

DevinUnderwood2
Occasional Contributor

Interesting I just added .split ("\\)

writer.writerow([fullpath.split("\\")])

I get the following which correctly splits it at the slashes and yields  commas.

['Sewer', 'ControlValve']

So, I only need to write to different rows where it is has a comma.

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

I handled that in my example

see line 5

if you have to do this, all it does is determine the length of the list (hence the len(b)) and multiplies the format designator {} the correct number of times, then adds a newline

hence.... line 5

this is equivalent to

use my c syntax

for i in c:

    writer.writerow(i)

and you are done

0 Kudos
DevinUnderwood2
Occasional Contributor

Thanks for the help

I put the following and results in vertical rather than horizontal and each letter is written to a different cell.

b = fullpath.split("\\")

c = ("{}\n" * len(b)).format(*b)

for i in c:

  writer.writerow (i )

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

simpler still... use b if you have to write one row at a time

for i in b: print(i)

...

Sewer

ControlValve

0 Kudos
DevinUnderwood2
Occasional Contributor

b = fullpath.split('\\')

c = ("{}\n" * len(b)).format(*b)

for i in b:

  writer.writerow(i)

This is one step closer. Yet writing into single cells and vertically.

S\"E"\"W"...

C\"O"\"N"...

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

grief... it obviously don't write the newline

so try to add it

writer.writerow( i + "\n" )

0 Kudos