Anomalous backslash in string VSC Python

1.9k Views Asked by At

So i was working on something and Visual Studio Code has spat out an error. I have tried several things but nothing seemed to work.

while True:
    try:
        file = open("{0}\..\state.txt".format(os.getcwd()), 'r', encoding = "utf-8")
        file.read()

VisualStudioCode-error.png

1

There are 1 best solutions below

2
On BEST ANSWER

Python uses the \ as the escape character so in your case, you'd have escaped the . and s. You need to do the following:

file = open(r"{0}\..\state.txt".format(os.getcwd()), "r", encoding="utf-8")

If you are using Python 3.4+, as @ninMonkey mentioned, you can also use pathlib.Path:

import pathlib

... your code here ..

file = open(pathlib.Path(os.getcwd(), "..", "state.txt"), "r", encoding="utf-8")```