提问人:PTDL Hermann Gmeiner - Lp 6A2 提问时间:5/6/2023 更新时间:5/7/2023 访问量:330
NameError:未在退出上下文中定义名称“path”
NameError: name 'path' is not defined in exiting context
问:
我运行以下代码并希望检查文件是否存在,但我遇到了错误。
这是我的代码:
paths = "Z:\PythonPratics\Library\BatKi.txt"
if path.exists(paths) == True:
myFile = open(paths,"r")
g = myFile.read()
myFile.close()
print(g)
else:
print("Cannot run because some file doesn't exist")
这里是错误的:
Traceback (most recent call last):
File "d:\Dayroi\PythonPratics\Test.py", line 3, in <module>
if path.exists(paths) == True:
^^^^
NameError: name 'path' is not defined. Did you mean: 'paths'?
你能帮忙吗?
我希望检查文件是否存在,但我遇到了错误。我将尝试不同的内置库,但我不知道哪个库最好。
答:
0赞
user17410204
5/6/2023
#1
在代码开头添加时,它应该可以工作:import os.path
import os.path
paths = "Z:\PythonPratics\Library\BatKi.txt"
if os.path.exists(paths) == True:
myFile = open(paths,"r")
g = myFile.read()
myFile.close()
print(g)
else:
print("Cannot run because some file doesn't exist")
评论
import os
if os.path.exists(paths):