字符串 VSC Python 中的异常反斜杠

Anomalous backslash in string VSC Python

所以我正在做一些事情,Visual Studio 代码吐出一个错误。 我尝试了几种方法,但似乎没有任何效果。

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

Python 使用 \ 作为转义字符,因此在您的情况下,您已经转义了 .和 s。您需要执行以下操作:

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

如果您使用的是 Python 3.4+,如@ninMonkey 所述,您还可以使用 pathlib.Path:

import pathlib

... your code here ..

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