简体   繁体   中英

Function open() doesn't work in Visual Studio Code

I have a few projects for which I have to edit .txt documents and I am using Visual Studio Code. When I just use the standard IDLE everything works fine, but when I try it in VS-Code I get the following error 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>

The Code used in the Test is:

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

Without being given a path name, open would try to find the given file name in the interpreter's current working directory, which in Visual Studio Code may be different from your IDLE environment.

Instead you should always pass to open the full path name to the file unless you are certain of the current working directory being the correct one (perhaps by calling os.chdir first).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM