2

I am trying to create a directory in my Python code but I can't use backslash \ in a string. Every time I do it gives me an unexpected token error.

I would like my code to look something like this:

dir = os.getcwd() + "\FolderIWantToCreate"

If I use / (forward slash), it gives me an error because my directory paths use backslash. However if I type \ (backslash) anywhere in my code, even inside "", it doesn't register the backslash as a string, it says unexpected token.

How can I overcome this?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Sarah Kay
  • 81
  • 5

6 Answers6

6

\ is the escape character in python. If you want to use \ in a string you have to escape it, i.e.:

"\\"

For more, see: https://docs.python.org/2.0/ref/strings.html

Wobli
  • 192
  • 14
4

You have two options:

  1. You can either escape the escape character \ by adding an extra \ before it, like this: "\\FolderIWantToCreate",
  2. You can use the r prefix before the string to tell python that the string that follows is a raw string, like this: r"\FolderIWantToCreate"
TheOneMusic
  • 1,776
  • 3
  • 15
  • 39
2

If you are dealing with paths and look e.g. for OS intercompatibility, consider using the pathlib package. More info on how to use it when e.g. creating new folders, see here.

If you really have to use that notation anyways, then an option would be to make it a "raw" string:

s = r'\FolderIWantToCreate'

more on that e.g. here.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
1

Please use the Escape sequence when ever you are using special characters

dir = os.getcwd() + "\\FolderIWantToCreate"

Reference : 2.4.1 String literals

Sundeep Pidugu
  • 2,377
  • 2
  • 21
  • 43
0

dir = os.getcwd() + "\\FolderIWantToCreate"

0x01h
  • 843
  • 7
  • 13
0

Just adding another answer which I think you should know;

Assuming you are on Windows

You can use os.path.join() with os.sep to overcome the issue you are facing.

I do not have a Windows VM with me to give you a concrete example.

ObiWan
  • 196
  • 1
  • 12
  • You don't need `os.sep`; `os.path.join` already uses it implicitly; `os.path.join(os.getcwd(), "FolderIWantToCreate")` does the job. – ShadowRanger Jul 22 '20 at 14:23