0

I wrote a very simple test that is failing:

with open('file.txt', 'r') as f:
    print(f.read())

While the file is very much there, it is giving an error:

FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

How am I supposed to setup the VSCode env to recognize the remote file system during execution? It does seem to be using the remote python interpreter.

2 Answers2

0

I found one solution I dont like. If I provide a fully qualified path the file will open, which means the interpreter is not running from the directory the code is in. Is there a way to tell the interpreter to run from a specific, or better yet, the script's directory?

This works:

import os

CWD = os.path.dirname(os.path.abspath(__file__))

with open(f'{CWD}/file.txt', 'r') as f:
    print(f.read())
0

You can use "Run without Debugging" and set up a configuration in your launch.json that use the "cwd" setting. That way you can specify where you want execution to take place from.

But if the specific goal is to read a file that exists next to source code I would recommend using importlib.resources to read the file as it will take care of the path resolution for you relative to the module.

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40