Error in Pathlib on Visual Studios Code

So the problem is that whenever I run file_reader.py (from Eric Matthes’s Python Crash Course) it tells me:

 File "C:\Users\My Name\AppData\Local\Programs\Python\Python314\Lib\pathlib\__init__.py", line 792, in read_text
    with self.open(mode='r', encoding=encoding, errors=errors, newline=newline) as f:
         ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\My Name\AppData\Local\Programs\Python\Python314\Lib\pathlib\__init__.py", line 776, in open
    return io.open(self, mode, buffering, encoding, errors, newline)
           ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

And just so you know “my name” is just a place holder for… well my name.
For reference, the file_reader.py is supposed to read pi_digits.txt. Here’s both of their codes:

from pathlib import Path
path = Path("pi_digits.txt")
contents = path.read_text().
print(contents)
3.1415926535
  8979323846
  2643383279

My best guess is that it has to do with the username of the user. Before it was “My Name” and I think the space was interfering with it, so I changed it to “Me” which did appear in some spaces but not, of course, the command prompt or Visual Studios.
However, I notice that there are some exceptions to this problem:

  1. So whenever I run it from the command prompt it… works just fine.
  2. If I do the ctrl + k + o thing that changes which files are shown and I change it to chapterten (where both file_reader.py and pi_digits.txt are) it also works just fine, which is probably because it doesn’t have the space in it there because it’s just that one folder.

I probably should note I’m very new to coding, so I don’t know much about this.
Thanks in advance to anyone who helps!

Hello,

the reason that it appears to work in his tutorial is that the file exists in the same working directory as the command prompt or the file’s directory is in the system’s PATH environment.

As a workaround and to verify that there is nothing wrong with the script, place the pi_digits.txt file on your Desktop directory.

Now modify your .py file as shown here and re-run it:

import os
os.chdir(r'C:\Desktop')  # Change working directory to `Desktop`

from pathlib import Path

path = Path("pi_digits.txt")
contents = path.read_text()
print(contents)

It should work now since the IDE path is the same as the file’s.

An alternative to forcing a change in the IDE's working directory is to provide the entire path of the text file (shown here for an arbitrary location):
path = Path(r"C:\the\working\directory\of\my\file\pi_digits.txt")

Hope this clears things up.