python - 函数 open() 在 Visual Studio Code 中不起作用

标签 python python-3.x function visual-studio-code

我有几个项目需要编辑 .txt 文档,并且我正在使用 Visual Studio Code。当我只使用标准 IDLE 时,一切正常,但是当我在 VS-Code 中尝试时,我收到以下错误代码:

Traceback (most recent call last):
  File "c:\Users\User\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\ptvsd_launcher.py", line 43, in <module>
    main(ptvsdArgs)
  File "c:\Users\User\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 432, in main  
    run()
  File "c:\Users\User\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 262, in run_path
    return (_run_module_code(code, init_globals, run_name, pkg_name=pkg_name, script_name=fname))
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 96, in _run_module_code
    _run_code(code, mod_globals, init_globals, mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\User\Desktop\VSCode\test.py", line 1, in <module>
    hlayers = open("hiddenvalues.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'hiddenvalues.txt'
PS C:\Users\User\Desktop>

测试中使用的代码是:

f = open("test.txt", "r")
print(f.read())

最佳答案

如果没有给出路径名,open 将尝试在解释器的当前工作目录中查找给定的文件名,该目录在 Visual Studio Code 中可能与 IDLE 环境不同。

相反,您应该始终将文件的完整路径名传递给 open ,除非您确定当前工作目录是正确的(也许通过调用 os.chdir > 第一)。

关于python - 函数 open() 在 Visual Studio Code 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59569823/

相关文章:

function - 在 Clojure 中传递带有参数作为参数的函数

javascript - 如何用自定义变量替换 DJANGO 中 JAVASCRIPT 脚本生成的 Google map key

python - 如何在 Python 中混合使用多个可选参数?

C 函数调用 : Understanding the "implicit int" rule

python - 使用 Twisted 创建和部署 Python 聊天应用程序

json - DRF - 序列化器多模型

c - 如何计算文本文件中相互重叠的单词

python - 有没有办法更改日志文件中运行的关键字的颜色,即使该关键字成功?

c++ - 将脚本语言集成到 C++ 应用程序中

python - 如何计算数据框中的 "actual"行?