2

I am trying to open each of the following files separately.

"C:\recipe\1,C:\recipe\2,C:\recipe\3,"

I attempt to do this using the following code:

import sys
import os
import re

line = "C:\recipe\1,C:\recipe\2,C:\recipe\3,"
line = line.replace('\\', '\\\\') # tried to escape control chars here
line = line.replace(',', ' ')
print line # should print "C:\recipe\1 C:\recipe\2 C:\recipe\3 "

for word in line.split():
    fo = open(word, "r+")
    # Do file stuff
    fo.close()

print "\nDone\n"

When I run it, it gives me:

fo = open(word, "r+") IOError: [Errno 13] Permission denied: 'C:'

So it must be a result of the '\r's in the original string not escaping correctly. I tried many other methods of escaping control characters but none of them seem to be working. What am I doing wrong?

pp_
  • 3,435
  • 4
  • 19
  • 27
  • You can also use, `os.path.normpath()` and use `/` instead, e.g. `paths = [os.path.normpath(p) for p in "C:/recipe/1,C:/recipe/2,C:/recipe/3".split(',')]`, `os.path.normpath()` will convert forward slashes to back slashes on windows. – AChampion Feb 28 '16 at 19:59

2 Answers2

2

Use a raw string:

line = r"C:\recipe\1,C:\recipe\2,C:\recipe\3,"
pp_
  • 3,435
  • 4
  • 19
  • 27
  • Note that a raw string still cannot end in a backslash. Not sure why that design decision was made. – Alyssa Haroldsen Feb 28 '16 at 19:53
  • Thank you for the answer! Your suggestion worked. However, is there a function to convert line into a raw string? Like raw(line)? – drspaceman0 Feb 28 '16 at 20:02
  • @drspaceman0 See https://stackoverflow.com/questions/7262828/python-how-to-convert-string-literal-to-raw-string-literal – pp_ Feb 28 '16 at 20:06
0

If for whatever reason you don't use raw string, you need to escape your single slashes by adding double slash:

line = "C:\\recipe\\1,C:\\recipe\\2,C:\\recipe\\3,"
print(line.split(','))

Output:

['C:\\recipe\\1', 'C:\\recipe\\2', 'C:\\recipe\\3', '']
idjaw
  • 25,487
  • 7
  • 64
  • 83