0

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

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49

1 Answers1

1

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")```




ewokx
  • 2,204
  • 3
  • 14
  • 27
  • or [pathlib.Path](https://docs.python.org/3/library/pathlib.html) handles that for you, as well as a cross platform way. – ninMonkey Jul 08 '20 at 01:02
  • @ninMonkey very true. That is only available for Python >= 3.4; so I took the basic method just in case the OP was still using Python 2.7 – ewokx Jul 08 '20 at 01:22