-1

Hello I am just a beginner in Python, and I got a problem with Pathlib in VSC So, I made this code in VCS basing on Python Crash Course:

from pathlib import Path
path = Path('pi.txt')
contents = path.read_text()
print(contents)

I got an error that this file does not exist. However, when I specify the path using '/absolute/path/to/pi.txt' it starts to work.

This code works like it should on PyCharm. But, can someone explain me why this does not work on VSC?.

Juan C
  • 5,846
  • 2
  • 17
  • 51
  • 3
    Check what's your current working directory, it probably isn't what you think it is, which means it won't find your file because it is looking at another folder – Juan C Jun 28 '23 at 15:59
  • if you want the directory where your script is you can get it with `Path(__file__).parent`. The path to your file would be `Path(__file__).parent / 'pi.txt'`. – Matthias Jun 28 '23 at 16:04
  • See: https://stackoverflow.com/questions/4060221/how-to-reliably-open-a-file-in-the-same-directory-as-the-currently-running-scrip – slothrop Jun 28 '23 at 16:13
  • Thank you everyone for the answers. It really helped me a lot (sorry for my English, it's not my primary language). – Zerk the Berg Jun 28 '23 at 16:21
  • Please check [ask] and pick a better title for your question... – Robert Jun 28 '23 at 16:30

1 Answers1

0

The issue you're encountering with Pathlib in Visual Studio Code (VSC) is likely due to the difference in working directories between the two environments.

When you provide a relative path like pi.txt, Pathlib assumes that the file is located in the current working directory.

However, the current working directory might not be the same in both PyCharm and VSC, To understand the current working directory in each environment, you can add the following code before your existing code:

from pathlib import Path
cwd = Path.cwd()
print(cwd)

Running this code will display the current working directory, which will help you determine where the script is looking for the file.

As a basic solution i suggest you to use a relative path based on the working directory as follow:

from pathlib import Path
path = Path.cwd() / 'pi.txt'
contents = path.read_text()
print(contents)

Best of luck mate