0

so I have just wanted to create a simple string but for some reason I get an error:

file_path = r"C:\Users\hadad\Desktop\webroot\imgs\"

whats wrong with that?

tomi
  • 45
  • 3

2 Answers2

0

Remove the leading \ to avoid to escape ":

file_path = r"C:\Users\hadad\Desktop\webroot\imgs"
#                                       HERE ---^

Or use:

file_path = "C:\\Users\\hadad\\Desktop\\webroot\\imgs\\"

file_path = "C:/Users/hadad/Desktop/webroot/imgs/"
Corralien
  • 70,617
  • 7
  • 16
  • 36
  • 1
    [The fundamental goal of closing duplicate questions is to help people find the right answer by getting all of those answers in one place.](https://stackoverflow.com/help/duplicates#:~:text=The%20fundamental%20goal%20of%20closing%20duplicate%20questions%20is%20to%20help%20people%20find%20the%20right%20answer%20by%20getting%20all%20of%20those%20answers%20in%20one%20place.) – mickmackusa Jun 04 '22 at 06:19
0

Interestingly, you cannot do that with a raw string:

Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, not as a line continuation.

https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

Instead, you might want to resort to the plain string literal:

file_path = 'C:\\Users\\hadad\\Desktop\\webroot\\imgs\\'
j1-lee
  • 10,540
  • 3
  • 12
  • 22
  • 1
    [The fundamental goal of closing duplicate questions is to help people find the right answer by getting all of those answers in one place.](https://stackoverflow.com/help/duplicates#:~:text=The%20fundamental%20goal%20of%20closing%20duplicate%20questions%20is%20to%20help%20people%20find%20the%20right%20answer%20by%20getting%20all%20of%20those%20answers%20in%20one%20place.) – mickmackusa Jun 04 '22 at 06:19